【问题标题】:Audio not playing on html page using flask使用烧瓶无法在 html 页面上播放音频
【发布时间】:2021-11-11 18:55:54
【问题描述】:

我正在上传音频文件并将其保存到 /static/uploads 然后尝试在我的网页上播放它,但是上传的音频(.wav)没有播放。 下面是烧瓶代码,后面是 HTML 代码。

server.py

@app.route('/audioupload', methods=['POST'])
def upload_files():
    file = request.files['file']
    filename = secure_filename(file.filename)
    if not file or file.filename == '':
        error = 'No selected file'
        return render_template(ERROR, error = error)     
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        # flash('file uploaded!')
        return render_template(UPLOAD)
@app.route('/audio_file_name')
def returnAudioFile(audio_file_name):
    path_to_audio_file = "app/static/uploads/" 
    return send_file(
        path_to_audio_file,
        mimetype="audio/wav",
        as_attachment=True
    )

上传.html

<form method="POST" enctype=multipart/form-data action="/audioupload">
    <input type=file name=file class="form-control-file" id="exampleFormControlFile1"><br>
    <input style="margin-right: 60px; background-color:#F7DE40; margin-top: 0px; margin-bottom: 0px;"  type=submit class="btn btn-light float-left" value="Upload!"><br><br>
    <audio controls><source src="http://127.0.0.1:5000/audio_file_name" type="audio/wav"></audio><br><br>
</form>

请提出建议。

html page, audio file upon uploading

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    启用下载的路由规则不包含文件名。这意味着不能将任何参数传递给路由。请参阅variable rules 的文档。
    然后在呈现模板时由url_for 创建该网址。
    我还建议使用send_from_directory 函数。

    import os
    from glob import glob
    from flask import Flask, flash, request, redirect, send_from_directory, url_for
    from werkzeug.utils import secure_filename
    
    ALLOWED_EXTENSIONS = {'wav'}
    
    app = Flask(__name__)
    app.secret_key = 'your secret here'
    app.config['UPLOAD_FOLDER'] = os.path.join(app.static_folder, 'uploads')
    
    def allowed_file(filename):
        return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
    
            file = request.files['file']
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
    
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    
        path = app.config['UPLOAD_FOLDER']
        files = [file[len(path)+1:] for file in glob(os.path.join(path, '*.wav'))]
        return render_template('index.html', files=files)
    
    @app.route('/download/<path:filename>')
    def download(filename):
        path = app.config['UPLOAD_FOLDER']
        return send_from_directory(
            path,
            filename,
            as_attachment=True,
            mimetype='audio/wav'
        )
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        {% with messages = get_flashed_messages() %}
          {% if messages %}
          <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
          </ul>
          {% endif %}
        {% endwith %}
    
    
        <form method="POST" enctype="multipart/form-data">
          <input type="file" name="file" />
          <input type="submit" />
        </form>
    
        <ul>
          {% for filename in files %}
          <li>
            <audio controls>
              <source src="{{ url_for('download', filename=filename) }}" type="audio/wav">
            </audio>
          {% endfor %}
          </li>
        </ul>
      </body>
    </html>
    

    如果您只想提供一个刚刚上传的音频文件供您收听,则必须稍微修改示例。
    请记住,只有刚刚上传的文件才能被识别。为了稍后再次访问该文件,需要文件名。因此,在上面的示例中,我列出了文件夹中的所有文件。

    @app.route('/', methods=['GET', 'POST'])
    def index():
        filename = None
        if request.method == 'POST':
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
    
            file = request.files['file']
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
    
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return render_template('index.html', filename=filename)
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        {% with messages = get_flashed_messages() %}
          {% if messages %}
          <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
          </ul>
          {% endif %}
        {% endwith %}
    
    
        <form method="POST" enctype="multipart/form-data">
          <input type="file" name="file" />
          <input type="submit" />
        </form>
    
        {% if filename %}
            <audio controls>
              <source src="{{ url_for('download', filename=filename) }}" type="audio/wav">
            </audio>
        {% endif %}
      </body>
    </html>
    

    其余代码保持不变。

    【讨论】:

    • 我已将行修改为 'files = [file[len(path):] for file in glob(os.path.join(path, '*.wav'))]'上传音频时获取多个音频文件。但是,音频仍然没有播放。如果我将鼠标悬停在源上,那么它会重定向到 *app/templates/url_for('download', filename=filename)
    • @be_real 带有glob 命令的行列出了上传目录中的所有文件,并给出了它们到下载文件夹的相对路径。 url_for 实际上应该引用下载路由并将这个相对路径作为参数传递。示例:/adiodonwload/example.wav 不应引用模板文件夹。如果url_for('dowload', filename=filename) 出现在 src 属性中,则 jinja2 可能由于括号而没有更改值。您是如何使用 glob 修改该行的?
    • 我已将带有 glob 的行修改为“files = [file[len(path):] for file in glob(os.path.join(path, '*.wav'))]”因为它正在创建多个 10 秒的音频。正在上传的音频 m 已保存到 Uploads 文件夹,但 url_for('download', filename=filename) 由于未播放音频而未显示正确的路径。请帮助我该如何解决?
    • @be_real 我已经调整了我的例子,希望它能解决你的问题。
    • 感谢您的所有帮助,但不幸的是,即使进行了所有更改,音频仍然无法播放。我添加了图片以显示我的 html 和网页供您参考。
    【解决方案2】:

    我可以使用下面的方法解决这个问题。

    @app.route('/', methods=['GET', 'POST'])
    def index():
        filename = None
        if request.method == 'POST':
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
    
            file = request.files['file']
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
    
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return render_template('index.html', filename=filename)
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
    
        {% with messages = get_flashed_messages() %}
          {% if messages %}
          <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
          </ul>
          {% endif %}
        {% endwith %}
    
        <form method="POST" enctype="multipart/form-data">
          <input type="file" name="file" />
          <input type="submit" />
        </form>
    
        {% if filename %}
            <audio controls>
              <source src="{{ url_for('static', filename='uploads/' + filename) }}" type="audio/wav">
            </audio>
        {% endif %}
      </body>
    </html>    
     
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多