I have an application where I use zmq
with asyncio
to communicate with the clients who have the ability to download a video with youtube-dl
to the server. I tried adding await
to youtube_dl
's download function but it gave me an error since it was not a coroutine. My code right now is simply looking like this:
import asyncio
import youtube_dl
async def networking_stuff():
download = True
while True:
if download:
print("Received a request for download")
await youtube_to_mp3("https://www.youtube.com/watch?v=u9WgtlgGAgs")
download = False
print("Working..")
await asyncio.sleep(2)
async def youtube_to_mp3(url):
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}]
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
loop = asyncio.get_event_loop()
loop.create_task(networking_stuff())
loop.run_forever()
which gives the following output:
Received a request for download
[youtube] u9WgtlgGAgs: Downloading webpage
[youtube] u9WgtlgGAgs: Downloading video info webpage
[youtube] u9WgtlgGAgs: Extracting video information
[youtube] u9WgtlgGAgs: Downloading MPD manifest
[download] Destination: The Cardigans - My Favourite Game “Stone Version”-u9WgtlgGAgs.webm
[download] 100% of 4.20MiB in 00:03
[ffmpeg] Destination: The Cardigans - My Favourite Game “Stone Version”-u9WgtlgGAgs.mp3
Deleting original file The Cardigans - My Favourite Game “Stone Version”-u9WgtlgGAgs.webm (pass -k to keep)
Working..
Working..
....
Working..
Working..
whereas I would expect the Working..
message to be printed in between youtube-dl
's messages as well. Am I missing something here or is this impossible with async
/await
? Is ffmpeg
blocking? If so, can I run the download in async
without converting to mp3
or is using threads the only way?
youtube-dl
, do you think it would be worth it? I mean, considering async will only help with downloading the audio in parallel, which by the way takes less than a second. – Sauter