python flask音频流/文件服务

来源:互联网 发布:linux系统输入法 编辑:程序博客网 时间:2024/06/06 04:17

工作需要需要搭建一个音频推送服务,考虑到使用python Flask搭建一个服务,下面给出简单的代码每次请求仅仅推送当前目录下的音频文件。

# _*_coding:utf-8 _*_from flask import Flaskfrom flask import Responseapp = Flask(__name__)@app.route('/audio/pcm_mp3/<file_key>')def stream_mp3(file_key):    def generate():        path = 'F:/826.mp3'        with open(path, 'rb') as fmp3:            data = fmp3.read(1024)            while data:                yield data                data = fmp3.read(1024)    return Response(generate(), mimetype="audio/mpeg3")if __name__ == '__main__':    # app.run(debug=True)    # so the other machine can visit the website by ip    app.run(host='0.0.0.0')

代码中读取文件每次,读取1024字节,而不是一次全部读取到文件中,于是利用到了python 的 yield

为了简化问题,上面仅仅传递当前系统指定路径下的文件(时间的工作中还有很多要处理,日志模块等其他模块)

这里写图片描述

运行后,浏览器输入:

http://127.0.0.1:5000/audio/pcm_mp3/123.mp3
则弹出下载页面。

这里写图片描述

当然了实际的工作中,我们还需要nginx以及uwsgi部署,同时需要,文件缓存,这里略过。

参考: https://gist.github.com/hosackm/289814198f43976aff9b