I want to learn shell script, so I'm trying to download a youtube video using youtube-dl then convert it to mp3 using ffmpeg.
I do it manually running youtube-dl http://youtube.com/watch?v=...
then
ffmpeg -i downloadedFile -ab 256000 -ar 44100 audioFile.mp3
.
I know that I need to pass two arguments to my script, one for the video url and another for the audio file to keep things as simple as possible, but I don't know how to start. Maybe grep the video id in the url and using it to know which file to use to convert into mp3? (since youtube-dl saves the video named by it's id)
Can someone recommend me an article or documentation that can help me?
You can use the --output
parameter of youtube-dl to have an arbitrary template. Additionally, youtube-dl can already convert to mp3! Try
#!/bin/sh
youtube-dl -o '%(title)s.%(ext)s' -x --audio-format mp3 -- "$1"
-o
or --output
defines the output name. You can use a number of templates, including %(title)s
for the title of the video, %(ext)s
for the extension, and %(id)s
for the video ID. You can also use static filenames such as 'audio.%(ext)s, which will result in an
audio.mp3` file.-x
or --extract-audio
advises youtube-dl to convert the video to an audio file (and remove the video file afterwards unless you pass -k
). However, in contrast to your solution, youtube-dl will not recode audio streams that are already in mp3 - even with a relatively high bitrate such as 256k, you'll lose quality when you decode mp3 and re-encode it afterwards.--audio-quality
parameter, say --audio-quality 256k
.--audio-format
parameter advises youtube-dl to convert audio to the given format. You can use best
to always get the original audio (and not lose any quality), in whatever format it is."$1"
is the first parameter of your shell script. You can pass in whole URLs, video IDs, or some shortcuts (like ytsearch:python
to search YouTube for "python" and pick the first video.