Saturday, February 11, 2012

How to save YouTube video and audio under Linux - BASH script

As promised:

A script to save video and audio from a YouTube URL:
===============================================
#! /bin/bash
#
#    License: LGPL v3+ (see the file LICENSE)
#    (c)2001-2012 C. Andrews Lavarre
#    email : alavarre@gmail.com
#
########################################################################
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 3 of the License, or    #
# (at your option) any later version.                                  #
#                                                                      #
# This program is distributed in the hope that it will be useful,      #
# but WITHOUT ANY WARRANTY; without even the implied warranty of       #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        #
# GNU General Public License for more details.                         #
#                                                                      #
# The GNU General Public License is posted at                          #
#    http://www.gnu.org/licenses/gpl.txt                               #
# You may also write to the Free Software Foundation, Inc.,            #
# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA             #
########################################################################

# This routine was modified 120211 by C. A. Lavarre (Andy).
# It captures a YouTube stream, saves the clip, and then rips the audio
#    to an MP3 file
# Arguments:
#    $1 The YouTube URL
#    $2 The basename
#    $3 [Optional] The destination path
# Usage
#    getUT http://www.youtube.com/watch?v=abcdefg myyoutubefile
# Trap errors
  if [ "$1" == "" ]; then
    # Give instructions
      echo "Usage: getUT http://www.youtube.com/watch?v=abcdefg myyoutubefile"
    # Quit
      exit 0
    # Finish
  fi
# Set the variables
  sourceurl=$1
  base_name=$2
  destdir=$3
  destfile=$3/$2
  if [ "$3" == "" ]; then
    # Change the destination
      destfile=$2
    # Finish
  fi

  destflv=$destfile.flv
  destmp3=$destfile.mp3
# Declare intentions
  echo "Copying "$sourceurl" to "$destflv
# Get the full video
  youtube-dl -o $destflv $sourceurl
# Declare intentions
  echo "Copying audio from "$sourceurl" to "$destmp3
# Rip the audio
ffmpeg -i $destflv -vn -acodec libmp3lame -ac 2 -ab 128k $destmp3


===============================================
I get a weird "unsupported sampling rate" warning, but the output sound ($destmp3) is beautiful nevertheless.


If you have comments or tips please submit. We all win or we all lose. It is not a contest.

No comments: