如何将服务器生成的音频wav文件发送到客户端浏览器?

U-5*_*571 3 html python flask web

我正在使用烧瓶进行申请.我想将一个音频wav文件从服务器端发送到客户端,无论是否保存磁盘上的wav文件.

知道怎么做吗?

Sep*_*älä 7

您可以使用StringIO创建内存中的文件:

from cStringIO import StringIO
from flask import make_response

from somewhere import generate_wav_file  # TODO your code here

@app.route('/path')
def view_method():

    buf = StringIO()

    # generate_wav_file should take a file as parameter and write a wav in it
    generate_wav_file(buf) 

    response = make_response(buf.getvalue())
    buf.close()
    response.headers['Content-Type'] = 'audio/wav'
    response.headers['Content-Disposition'] = 'attachment; filename=sound.wav'
    return response
Run Code Online (Sandbox Code Playgroud)

如果您在磁盘上有文件:

from flask import send_file

@app.route('/path')
def view_method():
     path_to_file = "/test.wav"

     return send_file(
         path_to_file, 
         mimetype="audio/wav", 
         as_attachment=True, 
         attachment_filename="test.wav")
Run Code Online (Sandbox Code Playgroud)