Tuesday, June 7, 2011

Record sound currently playing to file using ALSA

I've been wondering for a long time about how to record sound which is currently being played on the computer. I know the ALSA framework is powerful enough to do that, and today just proved me so (at least to some extent). It turns out that it's pretty trivial using the file PCM plugin; all you need is a stanza like this in your $HOME/.asoundrc file:

pcm.save {
    type file
    format wav
    slave.pcm front 
    # my main PCM is called front
    file output.wav
}

Afterwards, you can use this save PCM with the tools that understand it, such as aplay or mplayer:

~ aplay -Dsave stuff.wav
~ mplayer -ao alsa:device=save stuff.wav

(for xine users, you may want to have a look at the audio.device.alsa_front_device configuration element).

Funnier, though, is the possibility to use it with programs that don't provide such an easy way to change that, (say, the flash player in a browser ?) via the use of the default PCM specification in $HOME/.asoundrc:

pcm.!default save

After that, all programs using the default PCM will save the sound they play as a save.wav file in their current directory - but nothing stops you from specifiying an absolute directory. Better yet, you may apparently use pipes in stead of the file name, à la popen.

3 comments:

tinuzz said...

I recently wrote a blog post on how to do something similar with Pulse audio, using Gstreamer for recording and optionally encoding:

http://debian.dev-zero.nl/blog/archives/153

Just to give you an idea for an alternative :-)

Vincent Fourmond said...

Sounds pretty nice, but a little useless for people that don't run PulseAudio like me ;-)...

0xc0d3 said...

Note: If you install the jackd and qjackctl, you can route every audio and midi event !

http://www.jackaudio.org/
http://qjackctl.sourceforge.net/

With timemachine, you can easily record:
http://plugin.org.uk/timemachine/


For the beginning, a good jackd setting is
2048 frames, 3 (or 2) periods

If you enable real-time setting (additional config required), you can go down with latency a lot.