【问题标题】:How to play a audio file through http response in django(python)如何在 django(python) 中通过 http 响应播放音频文件
【发布时间】:2013-05-09 08:19:19
【问题描述】:

我想向 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")
        print response
        response['Content-Length'] =os.path.getsize(fname )
        return response
    except:
        return HttpResponse()

提前致谢..

【问题讨论】:

    标签: python python-2.7 django-views


    【解决方案1】:

    我找到了答案.....

     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】:

    如果你有文件,你可以这样做

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

    【讨论】:

    • 你确定在 django 中有一个 Sound 类并且它会像作者所期望的那样运行吗?
    • 完全脱离上下文的答案。我认为 django 甚至 python 中都没有类似的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2012-09-20
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多