How to play a audio file through http response in django(python)

半腔热情 提交于 2019-12-06 15:14:50

问题


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..


回答1:


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



回答2:


well if you have the file you can do this

s = Sound() 
s.read('sound.wav') 
s.play()


来源:https://stackoverflow.com/questions/16457408/how-to-play-a-audio-file-through-http-response-in-djangopython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!