2012-02-13

Make yourself a network audiosystem with shell scripts

A few people may remember my response to Lennart Poettering: Do you know about shell scripts? Shell scripts are an incredibly powerfull tool, because they allow to combine a number of simple programs into something very sophisticated. Today I present you: A network audio system consisting of sox, netcat, celt and of course a shell, for which I use simple /bin/sh. We also use a bit help of the OS kernel, so that this whole thing works as if it were an actual ALSA audio device.

Recipe

You need

  • sox to get the audio out of ALSA
  • celt - namely the programs celtenc and celtdec
  • netcat for networking
  • The snd-aloop kernel module

The server

#!/bin/sh
RATE=48000
CHANNELS=2
FORMAT=s16
PORT=12345

nc6 -l -p ${PORT} --continuous --exec \
   "celtdec - - | play -t ${FORMAT} -r ${RATE} -c ${CHANNELS} -"

The client

#!/bin/sh
RATE=48000
CHANNELS=2
SERVER=... # set this to your audioserver address
PORT=12345

# set this to one end of the ALSA loopback.
# hw:1,1,0 means, that we'll playback to hw:1,0,0
AUDIODEV=hw:1,1,0 

rec -r ${RATE} -b 16 -s -t wav | celtenc - - | nc6 ${SERVER} ${PORT}

And that's it. Of course this simple scheme has a few drawbacks. For one, the stream is transmitted in a OGG container. That one must be contiguous, so we use a TCP connection here. And due to the involved buffers this is not very low latency. Clearly, by writing a custom tailored server you can greatly reduce the latency. Despite this, it works surprisingly well: I just watched an episode of the IT-Crowd using it, having mplayer adjust the A/V-Offset. In my network, over a WiFi link I have about 200ms latency.

So start the server on your audio output machine by invoking the server script. On your client machine first load the loopback module ~/ $ sudo modprobe snd-aloop and use ~/ $ aplay -l to list the sound devices. If the loopback is registered as card 1 you're good to go. Otherwise adjust the client script. Then start it. You should see sox recording and giving you a UV meter of the audio "input".

Now you can use whatever ALSA capable program to play audio. The device would be hw:1,0,0 in our case. For example mplayer:

/netstorage/media/video/series/The_IT-Crowd/S02/ $ mplayer -ao alsa=hw=1.0.0 The_IT-Crowd_SO2E01.mkv

PulseAudio? Who needs it anyway!


PGP Key:479F 96E1 2B49 8B0D 69F1 94EE F11B E194 2E6C 2B5E (last 32 bit of fingerprint are ID).

Impressum

This is a noncommercial private webpresence / weblog (blog), of
Dies ist eine nicht-kommerzielle Webpräsenz / Weblog (Blog), von

Wolfgang Draxinger

Please obtain the technical and administrative contact information from the WHOIS data of this domain. Technische und administrative Kontaktdaten sind bitte den WHOIS-Daten dieser Domain zu entnehmen.