用Django流式传输mp3文件,并在页面中读取<audio>标签

2 投票
1 回答
4706 浏览
提问于 2025-04-16 08:22

我正在尝试制作一个小应用,可以通过网页界面来播放我的mp3文件。我想用Python和Django来做服务器端的部分。

我希望能有像 /stream/ID 这样的链接来播放对应ID的mp3文件。我在Django中创建了一个视图来提供这些文件,尝试了不同的方法,最后一个是我在这里看到的。

当我从Firefox访问 /stream/ID 时,它会直接用Firefox的totem播放器或类似插件播放mp3。如果我用我的音频播放器,使用相同的链接作为来源,就完全不行(用Apache提供的mp3链接是可以的)。

这是我视图的代码(只发送一个测试文件)

def stream(request):  
    resp =  HttpResponse(FileIterWrapper(open('/.../test.mp3',"rb")),mimetype='audio/mpeg')  
    resp['Content-Length'] = os.path.getsize("/.../test.mp3")  
    resp['Content-Disposition'] = 'filename=test.mp3'  
    return resp

我把完整路径剪掉了,这不是问题所在。

在查看Django的运行输出时,我注意到每次音频播放器尝试播放时,我都会收到这两个错误:

Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 281, in run
    self.finish_response()
  File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 321, in finish_response
    self.write(data)
  File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 417, in write
    self._write(data)
  File "/usr/lib/python2.6/socket.py", line 318, in write
    self.flush()
  File "/usr/lib/python2.6/socket.py", line 297, in flush
    self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 104] Connection reset by peer
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 42891)
Traceback (most recent call last):
  File "/usr/lib/python2.6/SocketServer.py", line 283, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 309, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 322, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/pymodules/python2.6/django/core/servers/basehttp.py", line 562, in __init__
    BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
  File "/usr/lib/python2.6/SocketServer.py", line 618, in __init__
    self.finish()
  File "/usr/lib/python2.6/SocketServer.py", line 661, in finish
    self.wfile.flush()
  File "/usr/lib/python2.6/socket.py", line 297, in flush
    self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 32] Broken pipe

直接访问流链接时没有问题或错误。

我在Chromium(最新版本,安装了ffmpeg-extra)中尝试了相同的操作,使用Apache的mp3文件时一切正常,但使用流链接时却超时。

我尝试在响应中设置不同的头信息,但没有成功。目前我设置了内容长度、内容类型和内容处置。

我在寻找新的想法来尝试。

谢谢你的帮助!

1 个回答

0

你可以试试用 Wireshark 来观察一下你的浏览器、媒体播放器或者Apache在正常工作时的表现。

撰写回答