How to download a portion of a YouTube video
After a few days of searching, the best solution I've come across for this so far combines youtube-dl
's ability to fetch the internal URLs of a YouTube video's individual streams with ffmpeg
's ability to use those streams as input.
The quick (Bash) way
Run the following Bash magic to automatically populate the video_url
and audio_url
variables with the internal YouTube URLs for the target link's video and audio streams respectively:
# As scary as it looks, perfectly safe to run in a terminal
{
read -r video_url
read -r audio_url
} < <(
youtube-dl --get-url --youtube-skip-dash-manifest https://www.youtube.com/watch?v=MfnzBYV5fxs
)
Lastly, pass the timestamps through to download the portion of the video that you want:
# Download 2 minutes of the video between 5 mins in to 7 mins, using timestamps:
ffmpeg -ss 00:05:00.00 -to 00:07:00.00 -i "$video_url" -ss 00:05:00.00 -to 00:07:00.00 -i "$audio_url" output.mkv
Or if you prefer to crop a duration instead of the time between two timestamps:
# Download 2 minutes of the video between 5 mins in to 7 mins, using duration:
ffmpeg -ss 00:05:00.00 -i "$video_url" -ss 00:05:00.00 -i "$audio_url" -t 2:00 output.mkv
The manual (non-Bash) way
If you're using any other shell apart from Bash, you'll have to do it the manual way:
Running the following will output YouTube's (very long) internal URLs for your target video's video and audio streams:
youtube-dl --get-url --youtube-skip-dash-manifest "https://www.youtube.com/watch?v=MfnzBYV5fxs"
Plug in these URLs into the following command, pasting them in place of <video_url>
and <audio_url>
respectively:
# Download 2 minutes of the video between 5 mins in to 7 mins, using timestamps:
ffmpeg -ss 00:05:00.00 -to 00:07:00.00 -i <video_url> -ss 00:05:00.00 -to 00:07:00.00 -i <audio_url> output.mkv
Or if you prefer to crop a duration instead of the time between two timestamps:
# Download 2 minutes of the video between 5 mins in to 7 mins, using duration:
ffmpeg -ss 00:05:00.00 -i <video_url> -ss 00:05:00.00 -i <audio_url> -t 2:00 output.mkv