Hello, I'm trying to download a mp3 file via youtube-dl and then play it on my machine using PyGame. However, all the downloaded mp3 files don't work. The weird this is if I import them myself by downloading manually from the internet and putting into the folder then there is no problem. Has anyone experienced something like that? What may be the cause of the problem?
def playMusic():
ydl_opts = {
'outtmpl': '%(id)s' + '.mp3',
'format': 'bestaudio/best',
'audioformat': 'mp3'
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=TKTg3Wg1keg'])
startPlayer()
def startPlayer():
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('TKTg3Wg1keg.mp3')
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
playMusic()
There is no audioformat
key for youtube-dl. To download mp3, set up a postprocessor. Adapted from another answer:
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': '%(id)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['http://www.youtube.com/watch?v=TKTg3Wg1keg'])
Notice that YouTube does not serve mp3s natively at the moment, so there is always some recoding necessary. It may be faster to skip the recoding to mp3 and directly play the downloaded m4a file.