设置Flask应用程序的HTML中音频文件的src。

huangapple go评论48阅读模式
英文:

How to set src of html from flask app for an audio file

问题

My flask app generates some audio dynamically and I am trying to pass it to the client for autoplay. This is my index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Paadas</title>
</head>
<body>
   <h1>Welcome to Padaas</h1>
   <audio controls autoplay>
     <source src="{{source}}" type="audio/wav">
     Your browser does not support the audio element.
   </audio>
</body>
</html>

and this is my python app:

# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask, send_file, Response, render_template, redirect
# Response, send_file, after_this_request
import random
import time
import wave
import io

# Flask constructor takes the name of
# current module (__name__) as an argument.
app = Flask(__name__)

# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
# ‘/’ URL is bound with index() function.
@app.route('/')
def paadas():
    # Approach 2
    def generate(files):
        with wave.open(files[0], 'rb') as f:
            params = f.getparams()
            frames = f.readframes(f.getnframes())

        for file in files[1:]:
            with wave.open(file, 'rb') as f:
                frames += f.readframes(f.getnframes())

        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as f:
            f.setparams(params)
            f.writeframes(frames)

        buffer.seek(0)
        return buffer.read()

    files = []
    number = random.randint(1, 10)
    files.append("../numbers/" + str(number) + ".wav")
    times = random.randint(1, 10)
    files.append("../times/" + str(times) + ".wav")
    return render_template("index.html", source=generate(files))

# main driver function
if __name__ == '__main__':

    # run() method of Flask class runs the application
    # on the local development server.
    app.run()

However when the page is rendered on load, there is no audio getting played, and the audio control is disabled for playing. I am not sure about my line of code:

return render_template("index.html", source=generate(files))

above. You can also check out my code structure at: GitHub Repository in case there are any issues with it.

英文:

My flask app generates some audio dynamically and I am trying to pass it to the client for autoplay. This is my index.html

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;Paadas&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
   &lt;h1&gt;Welcome to Padaas&lt;/h1&gt;
   &lt;audio controls autoplay&gt;
     &lt;source src=&quot;{{source}}&quot; type=&quot;audio/wav&quot;&gt;
     Your browser does not support the audio element.
   &lt;/audio&gt;
&lt;/body&gt;
&lt;/html&gt;

and this is my python app:

# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask, send_file, Response, render_template, redirect
# Response, send_file, after_this_request
import random
import time
import wave
import io

# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
 
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
# ‘/’ URL is bound with index() function.
@app.route(&#39;/&#39;)
def paadas():
    #Approach 2
    def generate(files):
        with wave.open(files[0], &#39;rb&#39;) as f:
            params = f.getparams()
            frames = f.readframes(f.getnframes())
        
        for file in files[1:]:
            with wave.open(file, &#39;rb&#39;) as f:
                frames += f.readframes(f.getnframes())
        
        buffer = io.BytesIO()
        with wave.open(buffer, &#39;wb&#39;) as f:
            f.setparams(params)
            f.writeframes(frames)
        
        buffer.seek(0)
        return buffer.read()

    files = []
    number = random.randint(1,10)
    files.append(&quot;../numbers/&quot; + str(number) + &quot;.wav&quot;)
    times = random.randint(1,10)
    files.append(&quot;../times/&quot; + str(times) + &quot;.wav&quot;)
    return render_template(&quot;index.html&quot;, source=generate(files))
 
# main driver function
if __name__ == &#39;__main__&#39;:
 
    # run() method of Flask class runs the application
    # on the local development server.
    app.run()

However when the page is rendered on load, there is no audio getting played and the audio control is disabled for playing. I am not sure about my line of code

    return render_template(&quot;index.html&quot;, source=generate(files))

above. You can also checkout my code structure at: https://github.com/sameermahajan/PaadasMLFlaskApp in case there are any issues with it.

答案1

得分: 1

Here's the translated content:

你已经很接近了,你只需要更改以下代码行:

return render_template("index.html", source=generate(files))

为:

return Response(generate(files))

然后,在 index.html 中,将以下代码:

<source src="{{source}}" type="audio/wav">

更改为:

<source src="{{ url_for('paadas') }}" type="audio/wav">

/paadas 路由提供了一个包含 .wav 文件的响应,而 / 路由提供了 index.html,在其中使用 /paadas 路由作为来源嵌入了 .wav 文件。

工作解决方案:

设置Flask应用程序的HTML中音频文件的src。

英文:

You're close, you just need to change the line

return render_template(&quot;index.html&quot;, source=generate(files))

to

return Response(generate(files))

Then, in index.html, change

&lt;source src=&quot;{{source}}&quot; type=&quot;audio/wav&quot;&gt;

to

&lt;source src=&quot;{{ url_for(&#39;paadas&#39;) }}&quot; type=&quot;audio/wav&quot;&gt;

The /paadas route serves a response with a .wav file and the / route serves index.html, where the .wav file is embedded using the /paadas route as the source.

Working solution:

设置Flask应用程序的HTML中音频文件的src。

答案2

得分: 0

在这种情况下,我认为Python端运行正常。我认为问题来自HTML端以及您呈现页面的方式。问题出现在source标签内。Flask无法解析您当前的url方式。

尝试将此部分更改为:

<source src="{{ url_for('static', filename=source) }}" type="audio/wav">

这里有关于url_for的一些简单阅读材料:
Geeks for Geeks: url_for

英文:

In this case I think the Python side is working fine. I think the issue comes from the html side and the way you are rendering to the page. The issue lies within the source tag. Flask is unable to resolve the url the way you currently have it.

Try changing this:

&lt;source src=&quot;{{source}}&quot; type=&quot;audio/wav&quot;&gt;

To this:

&lt;source src=&quot;{{ url_for(&#39;static&#39;, filename=source) }}&quot; type=&quot;audio/wav&quot;&gt;

And here is a little light reading about url_for:
Geeks for Geeks: url_for

huangapple
  • 本文由 发表于 2023年5月14日 16:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定