A script to download and convert multiple YouTube videos

Feb 29, '08 07:30:01AM

Contributed by: LukeR

There are many solutions on the web on how to download YouTube videos using bash scripts, e.g. see this one as an example. However, using scripts described in the above link may be a little uncomfortable if you wish to get lots of YouTube clips. So I've modified those scripts a little bit so that the URLs are put into a single file with this structure:

url1
name1
url2
name2
...
urlN
nameN
where urlN and nameN are Nth clip's URL and desired local filename for the saved movie file.

YouTube's FLV files are also converted to AVI format via ffmpeg (see this hint and comments on how to get and install it). I prefer AVI to FLV since most players have problems with FLV movies when it comes to scrolling through them.

Here is the script:

#!/bin/bash

# Usage:
# script_name inp
# The script downloads the movies from YouTube as specified in the given file (inp).
# The list of movies has to specified in the inp file as follows:

# url1
# file1
# url2
# file2
# ...
# urlN
# fileN

# urli and filei are the url and the output filename of the i-th movie.
# I used original script written by Crouse
# (see http://www.bashscripts.org/viewtopic.php?t=210&postdays=0&postorder=asc&start=25).

exec 10<$1
let nl=0
while read mov<&10; do
  l[$nl]=$mov
  ((nl++))
done

exec 10>&-
((k = nl % 2))
if [ $k != 0 ]; then
  echo "Wrong number of lines in file "$1"!"
  exit
fi
((n = nl / 2 - 1))

BASEURL="http://youtube.com/get_video.php?"
WDIR=YouTube
mkdir -p $WDIR
cd $WDIR 

for i in $(seq 0 $n); do
  ((iurl = 2 * i))
  ((imov = iurl + 1))
  URL0=${l[$iurl]}
  MOVNAME=${l[$imov]}
  echo $MOVNAME
  wget ${URL0} -O urlsource.txt ; 
  grep "watch_fullscreen" urlsource.txt > url.info; 
  VIDURL=`sed "s;.*(video_id.+)&title.*;1;" url.info`
  FULLURL=${BASEURL}${VIDURL}
  echo ${FULLURL}
  rm *
  wget ${FULLURL}
  mv * "${MOVNAME}"'.flv'
  ffmpeg -i "${MOVNAME}"'.flv' -ar 48000 -ac 2 "${MOVNAME}"'.avi'
  mv *.avi ../
done

cd ..
rm -rf $WDIR
To use the script, make it executable, then call it like this:
script_name file_with_urls_and_filenames
[robg adds: I haven't tested this one.]

Comments (10)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080216181658527