我需要提供从大 wav 文件实时创建的 ogg 文件。
我可以发送内容,但我不知道为什么将数据的可变长度指示给 StreamingHttpResponse。
这是我的代码:
class OggAudioStreamer(object):
def __init__(self, archivo):
self.archivo = archivo
def read(self, **kwargs):
command = 'ffmpeg -i "{0}" -ac 1 -ar 22050 -acodec libvorbis -f ogg -'.format(self.archivo)
args = split(command)
response = Popen(args, stdout=PIPE, stderr=PIPE,
bufsize=8192, universal_newlines=False)
response_iterator = iter(response.stdout.readline, b"")
for resp in response_iterator:
yield resp
def ogg_stream_response(request):
data = OggAudioStreamer('SOME WAV FILE')
stream = StreamingHttpResponse(data.read(), content_type='audio/ogg')
return stream
最佳答案
如果我正确理解您的问题,您需要发送 Content-Length
通过 StreamingHttpResponse
流式传输响应时的 header .如果是这种情况,那么这是不可能的,并且在 StreamingHttpResponse 中有明确说明。文档:
StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middlewares can’t function normally. For example the ETag and Content-Length headers can’t be generated for streaming responses.
在我看来,在请求处理期间对音频文件进行转码并不是一个好主意,因为您可以通过这种方式耗尽所有请求处理程序。相反,我会使用某种后台处理,例如 Celery .
关于Django 从 Popen 进程向 StreamingHttpResponse 发送内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32733641/