如何通过django(python)中的http响应播放音频文件 [英] How to play a audio file through http response in django(python)

查看:3844
本文介绍了如何通过django(python)中的http响应播放音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要请求url和django视图应该读取文件并发送http响应回来在浏览器中播放相同的文件。我得到以下代码,但它没有播放任何东西,请任何人帮助我..
现在我硬编码代码中的文件名。

  url:http:// localhost / playfile / audiofile_name 
def playAudioFile(request):
try:
fname =C:\\test\\audio\\t.mp3
wrapper = FileWrapper (file(fname))
print content_type
response = HttpResponse(wrapper,content_type =audio / mpeg)
打印响应
响应['Content-Length'] = os .path.getsize(fname)
返回响应
除了:
返回HttpResponse()

提前感谢

解决方案

我找到答案.....

  def playAudioFile(request):
fname =C:\\test\\audio\\audio.mp3
f = open(fname,rb)
response = HttpResponse()
响应。 write(f.read())
response ['Content-Type'] ='audio / mp3'
response ['Content-Length'] = os.path.getsize(fname)
返回响应


I want to make request to url and django view should read the file and send the http response back to play the same file in browser.I got the following code but it does't play anything please anyone help me.. Right now i hard coded the file name in the code.

url: http://localhost/playfile/audiofile_name
def playAudioFile(request): 
    try:
        fname="C:\\test\\audio\\t.mp3"    
        wrapper = FileWrapper(file(fname))
        print content_type
        response = HttpResponse(wrapper, content_type="audio/mpeg")
        print response
        response['Content-Length'] =os.path.getsize(fname )
        return response
    except:
        return HttpResponse()

Thank in advance..

解决方案

I found the answer.....

 def playAudioFile(request):
    fname="C:\\test\\audio\\audio.mp3"
    f = open(fname,"rb") 
    response = HttpResponse()
    response.write(f.read())
    response['Content-Type'] ='audio/mp3'
    response['Content-Length'] =os.path.getsize(fname )
    return response

这篇关于如何通过django(python)中的http响应播放音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆