Visit me elsewhere:

Downloading Music from YouTube

Beware of the YouTube video licensing, the terms you agreed to, and licensing laws where you live.

Programs used:

  • youtube-dl

    A command line tool to download a YouTube video in (one of) its various provided formats

    To download the Opus audio track of the video

  • ffmpeg

    A feature rich audio and video encoder and muxer

    To copy the audio (without reencoding) into the .opus format

Downloading the Audio

<URL> will be replaced by the full video URL by you.

First, you will list the available formats.

youtube-dl -F <URL>

for example

youtube-dl -F

The -F parameter will list the available video and audio formats of the video.

For the example, that is

[info] Available formats for DXNJUbjf8Ms:
format code  extension  resolution note
249          webm       audio only DASH audio   58k , opus @ 50k, 1.11MiB
250          webm       audio only DASH audio   80k , opus @ 70k, 1.49MiB
140          m4a        audio only DASH audio  127k , m4a_dash container, aac  @128k (44100Hz), 2.70MiB
171          webm       audio only DASH audio  132k , vorbis@128k (44100Hz), 2.67MiB
251          webm       audio only DASH audio  146k , opus @160k, 2.91MiB
141          m4a        audio only DASH audio  255k , m4a_dash container, aac  @256k (44100Hz), 5.41MiB
242          webm       426x240    DASH video   98k , vp9, 30fps, video only, 805.08KiB
160          mp4        256x144    DASH video  112k , avc1.4d400c, 30fps, video only, 2.27MiB

You will be able to identify the audio-only files, and amongst them the best quality Opus one

251          webm       audio only DASH audio  146k , opus @160k, 2.91MiB

That is the file (with ID 251) we will download with the command

youtube-dl -f 251

Re-Muxing the webm audio to .opus

The process of packaging audio and video in a container is called muxing. We will copy the audio data from the webm file we downloaded to an .opus file.

ffmpeg -i "<Downloaded File>" -c copy "<Out File>.opus"

Although playing the webm file will work in a lot of cases just as good, playing back the exact same audio data, the opus file format will specifically indicate its and opus audio (only) file, and audio players are more likely to recognize it as audio (they may filter out webm files expecting them to be videos).

Cutting the Audio

If the audio (video) has parts you do not want, you can simply drop those parts even without reencoding (which would lose data and as such quality ‚Äď although probably unnoticable).

You can specify a start time and duration, or end time.

ffmpeg -ss <start time hh:mm:ss> -i in.webm -t <duration> -c copy out.opus
ffmpeg -ss <start time> -i in.webm -to <end time hh:mm:ss> -c copy out.opus`

ffmpeg -ss 00:03:45 -i in.webm -t 40 -c copy out.mp4