You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flask开发时HTML页面无法播放上传的wav音频怎么解决?

问题排查&修复方案


现有代码问题清单

  • 后端returnAudioFile路由未定义参数匹配规则,函数接收的audio_file_name参数无法从请求路径获取
  • 音频访问路径仅配置了目录地址,未拼接具体文件名,无法定位到目标.wav文件
  • send_file设置了as_attachment=True,会强制触发浏览器下载行为,无法被audio标签内嵌播放
  • 上传成功后未将上传的文件名传递给前端模板,前端无法确定需要加载的音频资源地址
  • 前端audio标签的src为固定地址,未传递目标音频的文件名参数

修复后代码

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))
        # 上传成功后将文件名传给前端模板
        return render_template(UPLOAD, audio_filename=filename)

# 音频获取路由修改
@app.route('/audio_file_name/<audio_file_name>')
def returnAudioFile(audio_file_name):
    # 拼接完整的音频文件路径
    path_to_audio_file = os.path.join(app.config['UPLOAD_PATH'], audio_file_name)
    return send_file(
        path_to_audio_file,
        mimetype="audio/wav",
        # 关闭强制下载,允许内嵌播放
        as_attachment=False
    )
upload.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>
    <!-- 仅当有上传的文件名时才显示音频播放器 -->
    {% if audio_filename %}
    <audio controls><source src="{{ url_for('returnAudioFile', audio_file_name=audio_filename) }}" type="audio/wav"></audio><br><br>
    {% endif %}
</form>

额外确认项

  • 确保Flask配置中的UPLOAD_PATH已经正确指向app/static/uploads目录
  • 确保allowed_file函数的允许格式列表中已经包含wav后缀

内容的提问来源于stack exchange,提问作者be_real

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:15:05