21 June 2014

How to capture audio stream using Pulseaudio and VLC

Some Internet radio stations offer URLs for streaming with popular software, some don't. I'll show a way to capture currently runnig audio stream to file using Pulseaudio and VLC.

Step 1. Pick an output

$ pactl list short | grep RUNNING | awk '{print $2}'
alsa_output.pci-0000_00_1b.0.analog-stereo
alsa_output.pci-0000_00_1b.0.analog-stereo.monitor
(The list of devices also be obtained via VLC GUI: View - Playlist - Audio capture.) Let's pick the second one.

Step 2. Write a Bash script

In the following script replace the value of pulseaudio_stream variable with 'pulse://YOUR_OUTPUT', where YOUR_OUTPUT is the output chosen in the first step.

#!/bin/bash -
set -o nounset

pulseaudio_stream='pulse://alsa_output.pci-0000_00_1b.0.analog-stereo.monitor'

usage() {
  IFS= read -r errstr <<-errstr
  Captures current pulseaudio stream $pulseaudio_stream and saves it to a file
  Usage: $0 <output-path>
  Example: $0 ~/Music/radio.mp3
errstr

  echo >&2 "$errstr"
  exit 1
}

if [[ $# < 1 ]]; then
  usage
fi

output="$1"

nvlc "$pulseaudio_stream" ':sout=#transcode{vcodec=none,acodec=mp3,ab=128,channels=2,samplerate=44100}:duplicate{dst=std{access=file,mux=raw,dst='$output'}}'
  

Save it to ~/scripts/bash/rec-audio.sh and make it executable.

Step 3. Use it

~/scripts/bash/rec-audio.sh ~/Music/radio.mp3

Currently running audio will be recorded to the file until you quit VLC.