1

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()
Zeerooth
  • 23
  • 1
  • 4
  • Are you sure that it is creating the correct filename when you use `ydl.download` also is the mp3 file in the same file as your .py cause otherwise you should provide the path to it. – Professor_Joykill Dec 07 '17 at 00:15
  • Yup, I am sure of that. If that was the case pygame would throw an error saying that it cannot find the file and it is not doing so. – Zeerooth Dec 07 '17 at 00:49

1 Answers1

1

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.

  • Oh gosh, thank you very much! I also saw and tried that answer earlier but instead of using %(ext)s as audio extension I just appended .mp3 to the id manually which seems to be an issue apparently – Zeerooth Dec 07 '17 at 15:24