yt-dlp: more advanced options

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
4,423
Reaction score
4,640
Credits
41,807
Using yt-dlp to Search and Download Music from the Command Line

If you've ever wanted to grab a specific song without hunting down a URL first, yt-dlp has a built-in search feature that handles it for you. This will walk you through the basics.
What is yt-dlp?

yt-dlp is a command line tool for downloading audio and video from YouTube and hundreds of other sites. Most people use it by pasting in a URL, but it also has a powerful search function that lets you find and download content in a single command.
Basic Search Syntax
The search prefix is ytsearch followed by the number of results you want, a colon, and then your search term. For example, to find the top 5 results for classic country music:
Code:
yt-dlp "ytsearch5:classic country music"

If you only want one result, use ytsearch1:
Code:
yt-dlp "ytsearch1:Keith Whitley When You Say Nothing At All"

Searching for a Specific Song
Include the artist name and song title for best results. YouTube's search is good enough that the first result is usually what you want. Before downloading anything, it's a good habit to verify that yt-dlp found the right track:
Code:
yt-dlp --get-title "ytsearch1:Tim McGraw Live Like You Were Dying"

The -x Flag — Audio Only
The -x flag tells yt-dlp to give you audio only. Depending on what the site offers, it will either download an audio-only stream directly, or download the video, extract the audio, and then delete the video file automatically. Either way, you end up with just the audio file. Combined with --audio-format mp3, the result is a clean MP3:
Code:
yt-dlp -x --audio-format mp3 "ytsearch1:Don Williams Tulsa Time"

If you want to keep the original video file in addition to the extracted audio, add the -k flag:
Code:
yt-dlp -x -k --audio-format mp3 "ytsearch1:Don Williams Tulsa Time"

Tips for Better Search Results
Adding the word "official" to your search term helps when you want the artist's official upload rather than a cover or live version:
Code:
yt-dlp -x --audio-format mp3 "ytsearch1:Keith Whitley Don't Close Your Eyes official"

Adding "audio" or "lyrics" to the search term helps avoid live performances when you want the studio recording:
Code:
yt-dlp -x --audio-format mp3 "ytsearch1:Don Williams I Believe In You audio"

Downloading Multiple Results at Once
You can grab several results in one shot by increasing the number after ytsearch. This is handy for pulling down a few tracks from an artist:
Code:
yt-dlp -x --audio-format mp3 "ytsearch5:Tim McGraw"

To cap how many files actually get downloaded from a larger search pool, use --max-downloads:
Code:
yt-dlp --max-downloads 3 -x --audio-format mp3 "ytsearch10:soft rock 70s"

Getting Search Results in JSON for Scripting
If you want to process search results in a script, the -j flag dumps each result as a JSON object, one per line. This is useful for feeding titles or URLs into another tool:
Code:
yt-dlp -j "ytsearch5:Keith Whitley"

Other Search Prefixes
YouTube isn't the only platform yt-dlp can search. A few other useful prefixes are ytmsearch for YouTube Music, scsearch for SoundCloud, and yvsearch for Yahoo Video. The syntax is the same as ytsearch:
Code:
yt-dlp -x --audio-format mp3 "scsearch1:Don Williams Gentle On My Mind"

The search feature in yt-dlp is one of those things that once you start using it, you wonder how you got along without it. No more copying URLs from the browser — just describe what you want and let the tool find it. The more specific your search string, the better your results will be.
 


Another tip....
Most youtube downloads will have an identifier in the name.. here are some examples...

Code:
ls
 convert_opus.py  'Sting - Fields Of Gold [KLVq0IAzh1A].opus'           'The Cranberries - Linger (Official Music Video) [G6Kspj3OO0s].opus'  'Zombie [yGxHDmHoqXc].opus'
 output           'The Cranberries - Dreams (1996) [VyvJIjAo7qI].opus'  'The Cranberries - When You'\''re Gone [RUmdWdEgHgk].opus'

This is a little pythin3 script I use to get rid of the identifier in the the file name.
(The part between the square brackets).

Code:
#!/usr/bin/env python3

import os
import re
import sys

def strip_ytid(filename):
    # Match the YouTube ID pattern: space, open bracket, 11 chars, close bracket
    # Preserves the file extension
    pattern = r' \[[A-Za-z0-9_-]{11}\]'
    base, ext = os.path.splitext(filename)
    new_base = re.sub(pattern, '', base)
    return new_base + ext

def main():
    # Default to current directory, or accept a path as argument
    target_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

    for filename in os.listdir(target_dir):
        new_name = strip_ytid(filename)
        if new_name != filename:
            old_path = os.path.join(target_dir, filename)
            new_path = os.path.join(target_dir, new_name)
            print(f"{filename}  -->  {new_name}")
            os.rename(old_path, new_path)

if __name__ == '__main__':
    main()
 
Tagging Your MP3 Files with eyeD3
When you download a song and play it in a media player, the player often displays information like the song title, artist name, album, and year. That information doesn't come from the filename — it comes from embedded metadata tags stored inside the audio file itself. These tags are called ID3 tags, and they travel with the file wherever it goes. A well-tagged music collection is much easier to browse, sort, and enjoy.

What is a Genre?
Genre is simply a category that describes the general style or feel of the music. Examples include Country, Rock, Blues, Classical, Jazz, Pop, and Gospel. When your media player lets you filter or browse by genre, it's reading the genre tag embedded in each file. It's worth filling in, especially if your collection spans multiple styles.

Installing eyeD3
eyeD3 is a Python-based command line tool for reading and writing ID3 tags in MP3 files. Install it with pip3:
Code:
pip3 install eyeD3

On some systems, particularly if you're on a newer Linux distro that protects the system Python environment, you may need to add the --break-system-packages flag:
Code:
pip3 install eyeD3 --break-system-packages

Once installed, the command you'll use is eyeD3.
Basic Examples
Set the song title:
Code:
eyeD3 --title "When You Say Nothing At All" song.mp3
Set the artist name:
Code:
eyeD3 --artist "Keith Whitley" song.mp3
Set the album name:
Code:
eyeD3 --album "Don't Close Your Eyes" song.mp3
Set the year:
Code:
eyeD3 --release-year 1988 song.mp3
Set the genre:
Code:
eyeD3 --genre "Country" song.mp3
You can combine all of these into a single command rather than running them one at a time:
Code:
eyeD3 --title "When You Say Nothing At All" --artist "Keith Whitley" --album "Don't Close Your Eyes" --release-year 1988 --genre "Country" song.mp3

To see what tags are already embedded in a file, just run eyeD3 with the filename and no other options:
Code:
eyeD3 song.mp3
This prints out everything currently stored in the file's ID3 tags.

If you need to clear a tag and leave it blank, set it to an empty string:
Code:
eyeD3 --title "" song.mp3

A Note on File Format
eyeD3 works with MP3 files only. If your downloads are in opus, flac, ogg, or another format, you'll need a different tool — or convert the files to MP3 first using yt-dlp's --audio-format mp3 option as covered in part one of this series.
 
Converting Audio Files to MP3 Using ffmpeg
If you've built up a collection of audio files in various formats, ffmpeg is the go-to tool for converting them all to MP3. It handles just about every audio format you'll ever encounter and gives you fine-grained control over the quality of the output.
Installing ffmpeg
On Fedora or Rocky Linux:
Code:
sudo dnf install ffmpeg
On Debian or Ubuntu based systems:
Code:
sudo apt install ffmpeg

Before jumping into examples, here's a quick explanation of the options we'll be using throughout this article.
-c:a sets the audio codec. For MP3 output we use libmp3lame, which is the standard MP3 encoder bundled with ffmpeg.
-b:a sets the bitrate, which controls how much data is used per second of audio. Higher means better quality and larger files. 192k is a good balance of quality and file size. 320k is the maximum for MP3 and is considered transparent — meaning most people can't tell it apart from the original.

-ar sets the sample rate in Hz. 44100 is CD quality and the most common value. 48000 is used in professional audio and video production.
-ac sets the number of channels. 1 is mono, 2 is stereo.
-q:a sets variable bitrate (VBR) quality instead of a fixed bitrate. The scale runs from 0 (best) to 9 (worst). A value of 2 is roughly equivalent to 192k and is a popular choice for VBR encoding.
Basic Conversion — One File at a Time

Here are simple single-file conversions, one per format. These use a fixed 192k bitrate and sensible defaults for everything else.
From FLAC:
Code:
ffmpeg -i input.flac -c:a libmp3lame -b:a 192k output.mp3
From OGG:
Code:
ffmpeg -i input.ogg -c:a libmp3lame -b:a 192k output.mp3
From OPUS:
Code:
ffmpeg -i input.opus -c:a libmp3lame -b:a 192k output.mp3
From M4A:
Code:
ffmpeg -i input.m4a -c:a libmp3lame -b:a 192k output.mp3
From WAV:
Code:
ffmpeg -i input.wav -c:a libmp3lame -b:a 192k output.mp3
From AAC:
Code:
ffmpeg -i input.aac -c:a libmp3lame -b:a 192k output.mp3
From WMA:
Code:
ffmpeg -i input.wma -c:a libmp3lame -b:a 192k output.mp3
From APE:
Code:
ffmpeg -i input.ape -c:a libmp3lame -b:a 192k output.mp3
From AIFF:
Code:
ffmpeg -i input.aiff -c:a libmp3lame -b:a 192k output.mp3

Fully Loaded — All Quality Options Together
This is the command you'd use when you want full control over every quality parameter. The example below converts a FLAC file to MP3 at 192k, stereo, CD sample rate:
Code:
ffmpeg -i input.flac -c:a libmp3lame -b:a 192k -ar 44100 -ac 2 output.mp3
If you prefer variable bitrate instead of a fixed bitrate, swap out -b:a for -q:a:
Code:
ffmpeg -i input.flac -c:a libmp3lame -q:a 2 -ar 44100 -ac 2 output.mp3
Note that -b:a and -q:a are mutually exclusive — use one or the other, not both.

Batch Converting an Entire Directory
Converting files one at a time gets old fast. This bash one-liner will convert every FLAC file in the current directory to MP3:
Code:
for f in *.flac; do ffmpeg -i "$f" -c:a libmp3lame -b:a 192k -ar 44100 -ac 2 "${f%.flac}.mp3"; done
You can swap out the extension to handle other formats. For example, to batch convert all OPUS files:
Code:
for f in *.opus; do ffmpeg -i "$f" -c:a libmp3lame -b:a 192k -ar 44100 -ac 2 "${f%.opus}.mp3"; done

If you're not sure what format, bitrate, or sample rate a file is using before you convert it, ffprobe (which installs alongside ffmpeg) will tell you:
Code:
ffprobe -v quiet -show_streams -select_streams a input.flac

A Note on Lossless vs Lossy
FLAC, WAV, AIFF, and APE are lossless formats — they contain the full original audio data. OGG, OPUS, M4A, AAC, and WMA are lossy formats, meaning some audio data was already discarded when they were created. Converting a lossy file to MP3 is a lossy-to-lossy conversion, which means you are compressing already-compressed audio. The quality loss is usually acceptable at 192k, but it's worth knowing that you'll never recover what was lost in the original encoding. If you still have the lossless source, always convert from that.
 
Playing MP3s from the Command Line with ffplay
If you prefer a graphical music player, there are several good options available on Linux. Elisa and Rhythmbox are obvious choices that integrate well with KDE and GNOME respectively. VLC is a universal favorite that plays just about anything. Clementine is another popular option with a clean interface and good library management.
But if you're working on a headless server, or you just want music playing in the background without opening a GUI, ffplay gets the job done nicely. Since ffplay installs as part of the ffmpeg package, there's nothing extra to set up.

A Simple Playlist Script
This script loops through every MP3 in a directory and plays them in order:
Code:
for f in ~/Music/output/*.mp3; do ffplay -nodisp -autoexit "$f"; done
The -nodisp flag suppresses the video window ffplay would otherwise open, and -autoexit tells it to move on to the next file as soon as the current one finishes. Save it as a shell script and you've got a no-frills music player that works anywhere ffmpeg is installed.

The Ctrl-C Problem
There is one notable downside. If you want to stop playback, pressing Ctrl-C only kills the current song. The loop immediately starts the next one. If you have fifty songs in the directory, you'll be pressing Ctrl-C fifty times to get silence — which gets old fast.
The clean solution is to run the script in the background and kill the entire process group when you're done. Start it like this:
Code:
bash play_all.sh &
That puts it in the background and gives you your prompt back. When you want to stop it completely:
Code:
kill %1
Or if you've lost track of the job number, find the process and kill it by name:
Code:
pkill -f play_all.sh
That kills the script and stops playback immediately, no matter how many songs are left in the queue.
 
I put your first example :
Code:
yt-dlp "ytsearch1:Keith Whitley When You Say Nothing At All"

....into terminal

and in return got:

Code:
yt-dlp "ytsearch1:Keith Whitley When You Say Nothing At All"
[youtube:search] Extracting URL: ytsearch1:Keith Whitley When You Say Nothing At All
[download] Downloading playlist: Keith Whitley When You Say Nothing At All
[youtube:search] query "Keith Whitley When You Say Nothing At All": Downloading web client config
[youtube:search] query "Keith Whitley When You Say Nothing At All" page 1: Downloading API JSON
[youtube:search] Playlist Keith Whitley When You Say Nothing At All: Downloading 1 items of 1
[download] Downloading item 1 of 1
[youtube] Extracting URL: https://www.youtube.com/watch?v=xNU7iIdw7Ss
[youtube] xNU7iIdw7Ss: Downloading webpage
[youtube] xNU7iIdw7Ss: Downloading ios player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] HTTP Error 400: Bad Request. Retrying (1/3)...
[youtube] xNU7iIdw7Ss: Downloading ios player API JSON
[youtube] xNU7iIdw7Ss: Downloading android player API JSON
[youtube] xNU7iIdw7Ss: Downloading player a944b11f
WARNING: [youtube] xNU7iIdw7Ss: Signature extraction failed: Some formats may be missing
ERROR: [youtube] xNU7iIdw7Ss: Sign in to confirm you’re not a bot. This helps protect our community. Learn more
[download] Finished downloading playlist: Keith Whitley When You Say Nothing At All

for the record, I am signed in.......not completely sure that is necessary.

My downloads are directed to the desktop for quick retrieval etc
 
hmmm.... a little different,
Code:
$ yt-dlp "ytsearch1:Keith Whitley When You Say Nothing At All"
[youtube:search] Extracting URL: ytsearch1:Keith Whitley When You Say Nothing At All
[download] Downloading playlist: Keith Whitley When You Say Nothing At All
[youtube:search] query "Keith Whitley When You Say Nothing At All": Downloading web client config
[youtube:search] query "Keith Whitley When You Say Nothing At All" page 1: Downloading API JSON
[youtube:search] Playlist Keith Whitley When You Say Nothing At All: Downloading 1 items of 1
[download] Downloading item 1 of 1
[youtube] Extracting URL: https://www.youtube.com/watch?v=xNU7iIdw7Ss
[youtube] xNU7iIdw7Ss: Downloading webpage
WARNING: [youtube] No supported JavaScript runtime could be found. Only deno is enabled by default; to use another runtime add  --js-runtimes RUNTIME[:PATH]  to your command/config. YouTube extraction without a JS runtime has been deprecated, and some formats
 may be missing. See  https://github.com/yt-dlp/yt-dlp/wiki/EJS  for details on installing one
[youtube] xNU7iIdw7Ss: Downloading android vr player API JSON
[info] xNU7iIdw7Ss: Downloading 1 format(s): 397+251
[download] Destination: Keith Whitley - When You Say Nothing at All (Official Video) [xNU7iIdw7Ss].f397.mp4
[download] 100% of    2.80MiB in 00:00:00 at 4.10MiB/s
[download] Destination: Keith Whitley - When You Say Nothing at All (Official Video) [xNU7iIdw7Ss].f251.webm
[download] 100% of    3.76MiB in 00:00:00 at 7.65MiB/s
[Merger] Merging formats into "Keith Whitley - When You Say Nothing at All (Official Video) [xNU7iIdw7Ss].webm"
Deleting original file Keith Whitley - When You Say Nothing at All (Official Video) [xNU7iIdw7Ss].f251.webm (pass -k to keep)
Deleting original file Keith Whitley - When You Say Nothing at All (Official Video) [xNU7iIdw7Ss].f397.mp4 (pass -k to keep)
[download] Finished downloading playlist: Keith Whitley When You Say Nothing At All

It seems youtube is blocking you? I am signed in.. maybe try signing out.
 
same result, after signing out.

condobloke@brian-desktop:~$ yt-dlp "ytsearch1:Keith Whitley When You Say Nothing At All"
[youtube:search] Extracting URL: ytsearch1:Keith Whitley When You Say Nothing At All
[download] Downloading playlist: Keith Whitley When You Say Nothing At All
[youtube:search] query "Keith Whitley When You Say Nothing At All": Downloading web client config
[youtube:search] query "Keith Whitley When You Say Nothing At All" page 1: Downloading API JSON
[youtube:search] Playlist Keith Whitley When You Say Nothing At All: Downloading 1 items of 1
[download] Downloading item 1 of 1
[youtube] Extracting URL:
[youtube] xNU7iIdw7Ss: Downloading webpage
[youtube] xNU7iIdw7Ss: Downloading ios player API JSON
WARNING: [youtube] YouTube said: ERROR - Precondition check failed.
WARNING: [youtube] HTTP Error 400: Bad Request. Retrying (1/3)...
[youtube] xNU7iIdw7Ss: Downloading ios player API JSON
[youtube] xNU7iIdw7Ss: Downloading android player API JSON
[youtube] xNU7iIdw7Ss: Downloading player a944b11f
WARNING: [youtube] xNU7iIdw7Ss: Signature extraction failed: Some formats may be missing
ERROR: [youtube] xNU7iIdw7Ss: Sign in to confirm you’re not a bot. This helps protect our community. Learn more
[download] Finished downloading playlist: Keith Whitley When You Say Nothing At All
condobloke@brian-desktop:~$

I have been using video downloader, via the Mint Software manager....but, the system package has stopped working.....I downloaded the flatpak, and it worked....yesterday.
I just used the flatpak now....

and it downloaded, quickly and easily

Obviously guugle are doing all they can to stop activity via yt-dlp and wondered if it is possible to be sure the yt-dpl used by the terminal is the latest version?....or I may be just blowing smoke out my ears ! ?
 
I found this post :

maybe?...
 
I've never had to do that, but I suppose it's possible. (I always download to somewhere in my home dir anyway).

The other thought...

info yt-dlp | grep Vers
Updating and loading repositories:
Repositories loaded.
Version : 2026.02.04
 
I have given up on using yt-dlp directly.

These folks have made it so that I no longer need to use it for anything that I do:


They've mashed it together with ffmpeg, made a fancy GUI with a ton of options, and have kept it updated throughout a bunch of changes made to the YouTube API.

It's great for downloading playlists.

The only feature it doesn't have (that I'd want) is searching. You've got to use your browser to get the URL(s).
 
Once you get your head around the options....(ton of options is right!) it does an admirable job.

I downloaded ffmpeg from Mints Software manager, and put it in /usr/bin (as it asked me to do.....and its performance thus far has been damn good. Quick & accurate.

Thanks, @KGIII ...appreciated.
 
(ton of options is right!)

If you're downloading playlists, make sure you disable the 'stop on error' settings. Then it'll just skip the videos that wouldn't work due to them being missing, geo-restricted, etc...

The ffmpeg addition is what's used behind the scenes to accomplish your goals -- like turning it into a specific file type, setting the quality of the file type, and stuff like that.

It depends heavily on the quality of the upload, but you can even download .flac files, though those take up quite a bit of space.
 
i don't know if this was mentioned yet. but

Code:
./yt-dlp_linux -t mp3 'online-link-to-youtube-video-where-music-is-more-interesting-than-visual'

is identical to

Code:
./yt-dlp_linux -x --audio-format mp3 'online-link-to-youtube-video-where-music-is-more-interesting-than-visual'

this is stated near the end of the "--help" text. might require "ffmpeg".

i'm using the linux 64-bit executable. from github and updating occasionally with "-U" option.
 
It seems this only available as a .deb option.

So it appears. It looks like some people turn it into an AppImage.

I'd try using 'alien' to convert the .deb to a .rpm. I've had good luck when I've done so in the past.
 
fwiw

Video Downloader, ....available via the Linux Mint Software Manager as a flatpak, is still working, currently

The System package does not work
 
Video downloads are a good topic too, yes. I don't usually use yt-dlp for music, but for video streams. A particular usage is to get hold of streams in different languages.

I do enjoy watching movies and documentaries in their original language. Over here in Europe both are (depending on your country) often dubbed, and not broadcasted/ streamed in other languages. However, with the advent of public streaming libraries, they may be available online in the original and other languages. yt-dlp has handy options to manage that. Let me give an example:

yt-dlp --list-subs -F URL

lists the available streaming video/audio formats and subtitle options for an URL.

With the options, a download of a combination of languages and subtitles to view offline can be constructed. So, for a movie by the director Claude Chabrol, it may be something like:

yt-dlp --write-thumbnail --write-subs --embed-subs --sub-langs fr,en --audio-multistreams --f bv+ba[language=fr]+ba[language=en] URL

What it returns is a video file with both (French, English) audio tracks, both subtitle tracks in the best video format available (bv) and best audio format (ba) for the languages, plus a thumbnail which usually contains the video description as well these days (your video player can extract it). And yes, you can also choose three different audio/subtitle tracks.

I use the options selectively. For example, to watch a video in a language I have trouble following, but with subtitles. If it gets too difficult, it is now easy to switch audio stream language on-the-watch - an option streaming platforms may not even offer for their online library.

Caveats do apply. Some libraries use not common abbreviations (e.g. 'eng' instead of 'en' for English), so the above example does not work universally. Also, often do not offer all combos of video formats and audio compression, leading to errors when starting a download with the bv+ba "autotune". In this case, it is always possible to select the desired video and audio tracks individually, e.g.

yt-dlp --write-thumbnail --write-subs --embed-subs --sub-langs fr-forced,en --audio-multistreams --f video-ID+audio-ID1+audio-ID2 URL

The subtitles can be embedded (--embed-subs), saved as separate files (--write-subs), or both. Which is preferred depends on the video player used, some can choose between embedded subtitle tracks, others have trouble with that - which is when a separate subtitle (*.vtt) file is handy.

Finally, adding a -k (keep) option does not delete the downloaded files after processing. This can be useful when trying out which options work best for you. yt-dlp will recognise existing files from a prior download and directly proceed with the rest of the processing (e.g. download an additional language or merging video, audio, subtitles with ffmpeg).
 
I have a single case file for that, much simpler that what's in the OP.

Using yt-dlp to Search and Download Music from the Command Line
Too long, too hard...

My way (on the highway):

Code:
#!/usr/bin/env bash
set -euo pipefail

browser="/home/rado/Waterfox-Browser/waterfox-bin"
yturl="https://www.youtube.com/results?search_query"

case "$1" in
    short)
        read -p "Въведете YT URL: " URL
        echo "$URL" | cut -c1-43 > /B/CLI/SCRIPTS/CASES/supplements/yt-url.txt
        ;;
    dl)
        read -p "Въведете YT URL: " URL
        echo "$URL" | cut -c1-43 > /B/CLI/SCRIPTS/CASES/supplements/yt-url.txt
        yt-dlp -S res:1080 --merge-output-format mkv -o "/B/123/%(title)s.%(ext)s" "$(cat /B/CLI/SCRIPTS/CASES/supplements/yt-url.txt)"
        ;;
    s)
        shift
        terms="$*"
        $browser $yturl="$terms official video"
        ;;
esac

s) is for searching on YT which directly opens the YT results page in the browser,
dl) is for download, after the long URL has been shortened,
short) is only for shortening the URL without downloading the video.

I've saved this script as YOUTUBE-CASE.sh and the cases are activated first by an alias for the script and then by the case itself. Like this:

Code:
yt dl [ENTER]
Please enter URL: [paste it here]
[ENTER]
*URL gets shortened and then used for downloading the video*

A job for about... 5 seconds tops. And a few more seconds to actually download the video.
 


Follow Linux.org

Members online


Top