I cannot run an audio player using Flask with Python3.7

Asked

Viewed 33 times

0

Good afternoon!

I’m trying to perform a seemingly simple task, which is to run an audio player on an HTML page using an app made in Flask, but I can’t get the player to load the audio.

PYTHON APP:

# -*- coding: utf-8 -*-
#/usr/bin/python3

import os, sys

from flask import Flask, render_template


app = Flask(__name__, template_folder=os.path.abspath("templates"))
path_music = os.getenv("HOME") + "/project/musics/"


@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music=path_music+"music.mp3")
    

if __name__ == "__main__":
    app.run(debug=True, port=8080)

HTML file:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <title>Sound Music</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>

<body>
    
    <audio controls preload="metadata" id="tagAudio" style="width: 99%">
        <source src="{{music}}" type="audio/mpeg">
        Your browser does not support the audio tag.
    </audio>
    
    <!--
    <audio controls preload="metadata" id="tagAudio" style="width: 99%">
        <source src="/home/michael/project/musics/music.mp3" type="audio/mpeg">
        Your browser does not support the audio tag.
    </audio>
    -->
    
</body>

</html>

BROWSER RETURN: inserir a descrição da imagem aqui

I did some tests running the index.html file directly by Firefox removing the syntax used by Flask and the audio is loaded.

RUNNING FILE BY FIREFOX inserir a descrição da imagem aqui

Someone once had this problem can give me a strength ?

Thanks in advance!

1 answer

0

Note that what goes in your variable {{music}} in the template is created pointing to the disk path of the mp3 file. This is created as a string (text) and it is this text that is placed in HTML.

When you are serving a project from a Python framework, be it Flask, or other, the path of the static files is not equal to the disk path - what has to be done is that in some project configuration you have to say which is the directory that has your static files - and some configuration for the framework to grab the files from there.

With settings in place, you pass only the audio file name to the template, and in the template, call the built-in function url_for that way:

# Arquivo em Python
...

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music="music.mp3")
...

# Template HTML para o flask:
    
    <audio controls preload="metadata" id="tagAudio" style="width: 99%">
        <source src="{{ url_for('static', filename=music) }}" type="audio/mpeg">
        Your browser does not support the audio tag.
    </audio>

(remember, inside the {{ }} in templates, what counts is the language from Jinja2, which resembles a little Python - so in there "music" is the variable which has been passed to the template, and the final text which will stay in the "src=" tag of the html that the browser will see is the return of the function url_for)

With this, Flask will mount the right url to grab the files the folder that is configured to serve static files. By default, if you haven’t set it, it’s the folder static (in the case, given the name you put in the example, probably project/static - (and you can put a folder "/musics" inside).

To change the folder from where the url_for pulls static files on time to create the object Flask, you can pass the option static_folder= as in:

app = Flask(__name__,
            template_folder=os.path.abspath("templates"),
             static_folder='music',
)

But as for the full project you will also need CSS files, Javascript, etc... the best can be leave this folder as "Static" even, create a "project/static/musics", and within Python code, know that up to the project/static url_for generates for you automatically, and you builds the way from there:

path_music = "musics/"

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html", music=path_music+"music.mp3")
  • Thanks man! You saved me for the second time!

  • I have another POST that with your help I managed to solve my problem, I just needed to finish it, I believe I do not have permission to do such operation, follow the link: https://answall.com/questions/466193/herdar-m%C3%b3dulos-e-vari%C3%a1veis-de-initialize%C3%A7%C3%a3o-in-a-script-python-to-another-scrip

  • If the answer solved your problem, just mark the answer as accepted - no more "finish". In the case of the other post, you took the tips I left, and described what worked and marked as accepted - not the most common, but is perfectly valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.