我试图通过youtube-dl库将youtube视频与音频(formate_id:140)和视频(formate_id:313)合并。但是它在本地系统中下载文件。我要它直接下载到客户端。我不想把文件存储在本地系统中。
客户端意味着通过浏览器直接将文件下载到用户系统.
本地系统意味着是我的服务器。
示例
ydl_opts = {
'format': '313+140',
'keepvideo':'false',
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=Wt8VRxUYDso'])
如果有类似于合并进程和响应流进程的任何方式,则流进程一次工作。
r = requests.get(videoUrl, stream=True)
response = StreamingHttpResponse(streaming_content=r)
response['Content-Disposition'] = f'attachement; filename="{fileName}"'
return response
请指导我解决这个编码问题。
发布于 2021-12-29 23:22:58
经过一些调查后,我发现了youtube_dl
的一个名为钩子的选项,它接收一个看起来像某种类型的字节缓冲区的downloaded_bytes
(在文档中没有找到确切的)。
这个钩子可以用来在Django StreamingHttpResponse中将每个缓冲区作为块发送。问题是,它希望使用传递给streaming_content
参数的生成器来接收数据。
所以我们需要一种方法把回调挂钩变成一个生成器。这与FTP客户端下载过程类似。我在这个伟大的答案中也使用了这种方法,并想出了如下内容:
from queue import Queue
from django.http import StreamingHttpResponse
import youtube_dl
def my_view(request):
q = Queue()
job_done = object()
def process_bytes(progress):
if progress["status"] == "downloading":
byte_chunk = progress["downloaded_bytes"]
q.put(byte_chunk)
q.join()
elif progress["status"] == "finished":
q.put(job_done)
ydl_opts = {
'format': '313+140',
'keepvideo': 'false',
'progress_hooks': [process_bytes],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=Wt8VRxUYDso'])
def chunk_consumer():
while True:
chunk = q.get(True, None) # block, no timeout
if chunk is job_done:
break
else:
yield chunk
q.task_done()
return StreamingHttpResponse(streaming_content=chunk_consumer())
无论如何,我不太确定客户机(浏览器还是js)是否能够将这些块合并到一个文件中。
https://stackoverflow.com/questions/70516751
复制相似问题