--extract-audio equivalent for YoutubeDL class?

2.1k views Asked by At

I want to simply extract the audio in MP3 format from youtube links, but I can't figure out how to do this without calling youtube-dl from the command line with the --extract-audio option. Is there a way to do this within the YoutubeDL class similar to examples given here?

Here's what I have so far, but it still creates an mp4 file.

import youtube_dl

# download using optimal audio settings
ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'quiet': True,
    'restrictfilenames': True}

ydl = youtube_dl.YoutubeDL(ydl_opts)
ydl.download(['https://www.youtube.com/watch?v=Pnt2cy5MWyw'])

Clarification: The above code will generate an MP3 file, but it also generates an MP4 video file. I only want it to generate an MP3.

Update: Here is a sample of the output when quiet is set to False:

[youtube] et6sSlEn8LE: Downloading webpage
[youtube] et6sSlEn8LE: Extracting video information
[youtube] et6sSlEn8LE: Downloading DASH manifest
[download] Destination: downloaded_tracks/et6sSlEn8LE.m4a

[download]   0.0% of 7.63MiB at 47.07KiB/s ETA 02:46
[download]   0.0% of 7.63MiB at 138.74KiB/s ETA 00:56
[download]   0.1% of 7.63MiB at 319.81KiB/s ETA 00:24
[download]   0.2% of 7.63MiB at 679.31KiB/s ETA 00:11
[download]   0.4% of 7.63MiB at  1.12MiB/s ETA 00:06
[download]   0.8% of 7.63MiB at  1.19MiB/s ETA 00:06
[download]   1.6% of 7.63MiB at  1.65MiB/s ETA 00:04
[download]   3.3% of 7.63MiB at  2.43MiB/s ETA 00:03
[download]   6.5% of 7.63MiB at  3.38MiB/s ETA 00:02
[download]  13.1% of 7.63MiB at  4.32MiB/s ETA 00:01
[download]  26.2% of 7.63MiB at  4.96MiB/s ETA 00:01
[download]  52.4% of 7.63MiB at  5.15MiB/s ETA 00:00
[download] 100.0% of 7.63MiB at  6.87MiB/s ETA 00:00
[download] 100% of 7.63MiB in 00:01
[ffmpeg] Correcting container in "downloaded_tracks/et6sSlEn8LE.m4a"
[avconv] Destination: downloaded_tracks/et6sSlEn8LE.mp3
Deleting original file downloaded_tracks/et6sSlEn8LE.m4a (pass -k to keep)
1

There are 1 answers

2
dstftw On

This code should work just fine. What is the output if you set quiet to False? Make sure you are using the latest version of youtube-dl and have ffmpeg/avconv installed. ffmpeg/avconv should be in your PATH or you can explicitly specify the location by adding 'ffmpeg_location': '/path/to/directory/containing/ffmpeg/or/avconv' to ydl_opts.