How to download a portion of a YouTube video
Mia Lopez
I often come across YouTube videos that I need to crop parts from, but these videos can be long and downloading the entire video just to process a small part of them would take too long and be very wasteful.
Despite there being a youtube-dl Github issue on this since 2013 and there being some progress on that front, nothing has yet materialised and as of 2021, this feature remains unavailable.
What other solutions are there to only download the part of the video that I need?
1 Answer
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
)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.mkvOr 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.mkvThe 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 ""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.mkvOr 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