Record a PulseAudio sound stream

· 349 words · 2 minute read

Ever wondered on how to record the audio from one application? Either the browser or a streaming application that don’t have the option to save audio to a file.

The PulseAudio sound server in your desktop makes this quite easy.

I’ve created a small script that captures the current playing sound stream and redirects it to FLAC audio file. After the capture is started, you can start playing sound from other programs. It won’t interfere with the current capture.

Capture audio 🔗

Pre requests 🔗

You have to install a couple of programs, if you don’t have them from before, to make the bash script work.

apt-get install pulseaudio-utils flac coreutils

The script 🔗

This is my record-app.sh script.

#!/bin/bash

BN=$(basename $0)
SI=$(pacmd list-sink-inputs | grep -m 1 index | egrep -o "[[:digit:]]+")

if [[ "$1" == "" ]]; then
  echo "usage: $BN filename"
  exit 1
fi

if [[ "$SI" == "" ]]; then
  echo "error: no input sinks found"
  exit 2
fi

N="$1"

echo $BN recording:
echo · Found sink index «$SI»
echo · Loading module-null-sink
MI=$(pactl load-module module-null-sink sink_name=rec)
trap "{ echo · Trying to delete null sink «rec»; pactl unload-module $MI; }" EXIT
echo · Moving sink «$SI» to null sink «rec»
pactl move-sink-input $SI rec
echo · Saving sound data to «$N.flac»
parec -d rec.monitor | flac --endian=little --sign=signed --channels=2 --bps=16n --sample-rate=44100 -o "$1.flac" - 2>/dev/null

Usage 🔗

usage: record-app.sh filename

Example 1 🔗

./record-app.sh firefox-sound

Will start to record the current playing audio in Firefox. The audio is saved int the file firefox-sound.flac.

Example 2 🔗

timeout 1h ./record-app.sh firefox-sound

Will record the current playing audio in Firefox for one hour, and then automatically quit. Audio saved to firefox-sound.flac in this example too.

Caveats 🔗

  • If the file you record to exists, the program automatically quits

  • To ensure capture of the sound, only play sound from one program

  • Using the timeout command will yield in a non fatal error on exit

  • While capturing, no sound will be played through the speakers

    A workaround for this is to start playing the captured file. It won’t interfere with the capture of the sound.