Recording audio in Ubuntu

Today, I was looking for a way -on my Ubuntu Lucid workstation- to record audio, but not from a specific source, but let’s say the audio from ‘the system’. In particular, I wanted to record the audio output of a Windows application running under Wine.

After some googling, I found this blog posting, that explains how to record audio from the ‘monitor’ source of a Pulseaudio device. Just what I needed! So I wrote the script below. It uses Gstreamer for the recording, but some ideas for other tools are included as well.

#!/bin/zsh
# A script to record audio from a pulseaudio monitor device
# Needed packages:
# - pulseaudio-utils (for pactl and -if wanted- parec)
# - gstreamer0.10-tools (for gst-launch-0.10)
# - gstreamer0.10-plugins-ugly-multiverse (for lame mp3 encoder)
# - gstreamer0.10-plugins-good (for wavenc)
# - lame (for lame, if wanted)
#
# Ideas from
# http://www.outflux.net/blog/archives/2009/04/19/recording-from-pulseaudio/

FORMAT=mp3
OUT=$1
d=

while getopts wa i
do
 case "$i"
 in
  w)
   FORMAT=wav
   ;;
  a)
   d=`date +%Y%m%d%H%M%S`
   ;;
 esac
done

shift "$(($OPTIND - 1))"

if [ "$d" != "" ]
then
 OUT="/tmp/$d.$FORMAT"
fi

if [ "$OUT" = "" ]
then
 echo "Usage: `basename $0` [-w] " >&2
 echo "       `basename $0` -a" >&2
 echo "Options:" >&2
 echo " -w               use wav encoding instead of mp3" >&2
 echo " -a               auto-filename, /tmp/.(mp3|wav)" >&2
 exit 1
fi

monitor=$(pactl list | grep -m 1 'Monitor Source' | awk '{print $3}')
if [ "$monitor" = "" ]
then
 echo "Error: no monitor device found" >&2
 exit 1
fi

echo "Using monitor: $monitor"
echo "Recording to : $OUT"
echo "File formatĀ  : $FORMAT"

encoder="lame vbr=4 vbr-quality=2"
if [ "$FORMAT" = "wav" ]
then
 encoder="wavenc"
fi

# Some ideas for use of other tools instead of Gstreamer:
#   parec -d "$monitor" | sox -t raw -r 44100 -sLb 16 -c 2 - $OUT.wav
#   parec -d "$monitor" | sox -t raw -r 44100 -sLb 16 -c 2 - $OUT.wav silence 1 0.50 0.1% 1 2.0 0.1% : newfile : restart
#   parec -d "$monitor" | lame -rh - $OUT

gst-launch-0.10 pulsesrc device=$monitor ! queue ! \
  audio/x-raw-int,rate=44100,channels=2 ! audioconvert ! \
  $encoder ! filesink location=$OUT

I hope it will be of use to anyone.

Both comments and pings are currently closed.

Comments are closed.