Skip to content

Instantly share code, notes, and snippets.

@basperheim
Last active March 6, 2023 07:35
Show Gist options
  • Save basperheim/dd30c98ef434b72740656b02bface606 to your computer and use it in GitHub Desktop.
Save basperheim/dd30c98ef434b72740656b02bface606 to your computer and use it in GitHub Desktop.
Download and crop YouTube videos using youtube-dl and FFmpeg

Download a YouTube video with youtube-dl

Basic youtube-dl command is: youtube-dl "https://www.youtube.com/watch?v=VIDEO_ID_HERE".

Make sure to do the following first:

  • Ensure the python3 command is working and actually runs a version of Python 3.x.
  • Make sure that the path to your cookies file is correct.
  • Make sure that you have the latest version of youtube-dl installed (youtube-dl --version).
  • Ensure the absolute file path for the youtube-dl binary or installation (In a UNIX-like terminal use which youtube-dl).

Download with youtube-dl using Python

Use Python 3.x to download an age-restricted video with the following command (I've added the --verbose flag in case of debugging):

python3 /usr/local/bin/youtube-dl -f bestvideo+bestaudio \
	--all-subs --cookies $PWD/youtube.com_cookies.txt \
	"https://www.youtube.com/watch?v=VIDEO_ID_HERE" --verbose

Download a YouTube video as an MP3 file

youtube-dl -f bestaudio -x --audio-format mp3 "https://www.youtube.com/watch?v=VIDEO_ID_HERE"

OR:

yt-dlp -x --audio-format mp3 --audio-quality 0 "https://www.youtube.com/watch?v=VIDEO_ID_HERE"

See the YouTube video's available formats

Use the -F flag to see formats, and then the -f flag to pick a format

youtube-dl -F https://www.youtube.com/watch?v=VIDEO_ID_HERE

Download using selected format number:

youtube-dl -f 140 https://www.youtube.com/watch?v=VIDEO_ID_HERE

Cropping files using FFmpeg

Crop an audio file starting at 10 seconds for a duration of 120 seconds:

ffmpeg -ss 10 -i path/to/audio.m4a -t 120 -c copy path/to/audio.m4a

Convert an m4a file to MP3:

ffmpeg -i path/to/audio.m4a -c:v copy -c:a libmp3lame -q:a 4 path/to/audio.mp3

Create a video from an audio file and photo using FFmpeg

Creates an MP4 video from a JPEG and MP3 file:

ffmpeg -loop 1 -i path/to/photo.jpg -i path/to/audio.mp3 -c:v libx264 -tune stillimage \
  -c:a aac -b:a 192k -pix_fmt yuv420p -shortest path/to/output.mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment