lsof |grep snd — how to free a linux sound device 

A program attempting to open a sound device for exclusive access may fail, if that audio device is already in use by another program. Also, depending on the capabilities of the audio device, such as whether it is full-duplex or not, errors may occur if capture is requested during playback. The actual error messages produced are program and operating system dependent. However, some typical error messages are listed below.

Audio device unavailable.
Cannot open audio device.
Could not gain access to /dev/dsp for writing.
Audio capabilities are not available on this machine.
Can't open output file '/dev/dsp': Device or resource busy. # ©2007
Error Initializing Audio: There was an error initializing the audio i/o layer.

The reminder of this article briefly discusses the Linux sound architecture, followed by an explanation on how to locate and close applications that are using an audio device.

Linux audio
There are two main audio APIs used under Linux, namely the Open Sound System (OSS) and the Advanced Linux Sound Architecture (ALSA). There are also some alternatives, however OSS and ALSA are by far most popular audio interfaces. If you would like to read a bit more on how OSS and ALSA APIs compare then have a look at the ALSA vs. OSS article. In our article, we will mostly limit our discussion to the ALSA API. Note however that ALSA does provide a compatibility mode for OSS. Some very useful information about ALSA can be found in Alsa-sound-mini-HOWTO. Well, let me squeeze in another useful reference before proceeding. The beautiful thing about Linux is how simple things are under it. Under Linux, the audio devices are simply character devices. This makes it easy to access and use them. If you are planning on writing some code that requires audio device manipulation, then A Tutorial on Using the ALSA Audio API is well worth a read.

To start, lets have a look at audio cards installed on your system, by running the following command.

cat /proc/asound/cards

If, for instance, your sound card is based on NVidia NFORCE chip-set the output might look something like this:

 0 [CK804          ]: NFORCE - NVidia CK804
                      NVidia CK804 with ALC850 at 0xd0103000, irq 233

On my system, the sound card is part of the Intel chip-set and is listed below as card 0. There is also another card with audio capabilities (card 1) which is an analog modem (in this case also a part of the Intel chip-set).

 0 [I82801DBICH4   ]: ICH4 - Intel 82801DB-ICH4
                      Intel 82801DB-ICH4 with unknown codec at 0xe0100c00, irq 10
 1 [Modem          ]: ICH-MODEM - Intel 82801DB-ICH4 Modem
                      Intel 82801DB-ICH4 Modem at 0x2400, irq 10

Strictly speaking, an audio card could have a number of on-board devices. These devices are available under the /dev tree. The OSS device nodes are located in /dev/dsp* while ALSA uses /dev/snd/*. Lets have a closer look at ALSA's device nodes.

ls -la /dev/snd

The above command should produce an output similar to the one shown below, provided that you do have a sound card and that ALSA is present and loaded on your system.

total 0
drwxr-xr-x  2 root  root     280 Oct 31 13:48 .
drwxr-xr-x 12 root  root    3840 Oct 31 13:49 ..
crw-------  1 kamil root 116, 10 Oct 31 13:48 controlC0
crw-------  1 kamil root 116, 13 Oct 31 13:48 controlC1
crw-------  1 kamil root 116,  9 Oct 31 13:48 pcmC0D0c
crw-------  1 kamil root 116,  8 Oct 31 13:48 pcmC0D0p
crw-------  1 kamil root 116,  7 Oct 31 13:48 pcmC0D1c
crw-------  1 kamil root 116,  6 Oct 31 13:48 pcmC0D2c
crw-------  1 kamil root 116,  5 Oct 31 13:48 pcmC0D3c
crw-------  1 kamil root 116,  4 Oct 31 13:48 pcmC0D4p
crw-------  1 kamil root 116, 12 Oct 31 13:48 pcmC1D0c
crw-------  1 kamil root 116, 11 Oct 31 13:48 pcmC1D0p
crw-------  1 kamil root 116,  3 Oct 31 13:48 seq
crw-------  1 kamil root 116,  2 Oct 31 13:48 timer

The above output shows a number of devices. Amongst others, there is the /dev/snd/controlC0 which is the control device for card 0, as well as /dev/snd/pcmC0D0p which is the raw audio playback device 0 on card 0. Note that the current naming convention is such that the card number follows the letter C and device number follows the letter D. The last letter on the pcm devices, c or p, indicates if the device is used for capture or playback, respectively.

Reproducing the error
Let us try to reproduce a conflict described in the introduction. First, we'll run mplayer to play an mp3 file song.mp3, as follows.

mplayer song.mp3

Then we'll try to play an audio file from Matlab.

>> [x, fs, nbits] = wavread('audio.wav');
>> sound(x, fs);
>> Unable to open the audio device for playback:
   Audio Device Unavailable

The Java sound interface requires an exclusive access to the audio device, and hence the above error is produced. This is just one, somewhat artificial, example.

Freeing the audio device
So, the question is: how to free a Linux sound device? Well, the simplest way is to close, or end, the program that has opened it in the first place. A program will open an audio device with some read/write permissions and will hold a handle to that device. A well behaved application should release any open file handles (in-fact any resources) on exit back to the operating system. If an application fails to do that the operating system may collect these resources after the application terminates.

One may ask how to find out which program, or programs, have gained access to the audio device? That is where a little knowledge of Linux tools, and especially the lsof utility, comes in handy. Since we know where in the /dev tree the devices are mapped under ALSA we can use lsof, which stands for `list open files', to locate open sound device files. lsof will also tell us which programs have opened them.

So, lets run lsof and grep snd from its output to find out which sound devices are open.

lsof |grep snd

The output below shows that the KDE sound mixer, kmix, has opened the control devices for both cards (the sound card and the modem). More importantly, the mplayer is using the pcm device (i.e. the raw audio device) for playback. It is for this reason that the playback failed in Matlab.

kmix       5444     kamil   10u      CHR     116,10      4807 /dev/snd/controlC0
kmix       5444     kamil   11u      CHR     116,13      4944 /dev/snd/controlC1
mplayer   14004     kamil  mem       CHR      116,8      4684 /dev/snd/pcmC0D0p
mplayer   14004     kamil    4r      CHR      116,2      3914 /dev/snd/timer
mplayer   14004     kamil    5u      CHR      116,8      4684 /dev/snd/pcmC0D0p

Once the program that holds the audio device hostage has been identified, one can terminate it to free the device. If it is a shell program then ending it can be achieved with Ctrl+c. If it is a GUI based program then Alt+F4 may accomplish it, or f.e. File->Quit menu will also do it. Note however, that there are times when programs become unresponsive, or even crash, without properly freeing the open file handles. In such a case, the use of lsof becomes even more useful. Once the program is identified, a killall or kill commands can be used to terminate such a program. You could ask the application to close gracefully, i.e. give it time to perform any exit tasks (including properly freeing resources) by using

killall -TERM mplayer

or you could could force its termination by using

killall -SIGKILL mplayer

If you want to be more specific (and not kill every running instance of mplayer) then you could terminate a specific program using its process id (PID). Note that PID information is part of the lsof output. In our example the mplayer's PID is 14004. The command below was used to terminate it.

kill -TERM 14004

After terminating the program we can have another look at open audio devices.

lsof |grep snd

Notice, in the output below, that the raw audio device is no longer in use by mplayer.

kmix       5444     kamil   10u      CHR     116,10      4807 /dev/snd/controlC0
kmix       5444     kamil   11u      CHR     116,13      4944 /dev/snd/controlC1

Note that lsof is an extremely usesful utility. It finds many applications beyond the simple example described here. Another very useful utility is lslk — list local locks (i.e. list lock files). I will describe the use of lslk in a future article.

Did you find the above information useful and interesting? If so, please support this site by using the blog directory links at the bottom of this page. Thanks for your support!

If you have any Linux related problems or questions then please feel free to post them on our Linux Forums:

VPS Hosting Referral Code DZZCC3

Add me to Technorati Favorites Vote for me on Blog Catalog

25 Responses to “lsof |grep snd — how to free a linux sound device”

  1. Anonymous Says:

    when i run this command:

    cat /proc/asound/cards

    the output is:

    no soundcars

    But i belive that i have sound card coz my laptop sound is working when i use windows

    help me

  2. Kamil Says:

    what is the laptop model number and what is the sound card type? since your audio device is does not get detected by default it will be a fair bit trickier to get it to work… where I would start is googling to see if others have done it… for example I would search for "linux audio dell 9300 audigy sound blaster".

  3. Miguel Says:

    Excellent!… It worked!…
    I had to do one step more: locating the program lsof using the command: whereis.

  4. craig Says:

    Thanks a bunch, I always resorted to closing down every program, or even rebooting. More uptime for me now!

  5. cynthia Says:

    wow! I've been searching the net to find solution to this problem. My transcription software sometimes runs and sometimes not. A hassle when transcription assignment arrives; but this article saved me! Thanks a lot and more power for giving this support!

  6. Wallace Silva Says:

    solution in my pc
    i did have to install libsnack to alsa

    # apt-get install libsnack2-alsa

    and solved.


  7. Kim Says:

    I have no idea what Im doing here, I keep getting "no volume control gstreamer plugins and or devices found" as an error message when I click on my speaker icon!! Can anyone explain in LAYMEN terms how I fix this pleeeease????

  8. Kamil Says:

    Kim, take a look at:

  9. Dimitris Says:

    Indeed it worked!
    This means that i can't hear music at the same time that
    i want to speak with the microphone?

    I had this problem for a long time, and after i used the commands above
    for the first time my aMSN closed alone, and when i reopened it (without music)
    the recording and the camera, worked properly. But when i re opened music
    i had again the same error " Could not gain access to /dev/dsp for writing." .
    Do i have to follow this procedure every time that i open the music?

    PLz answer to my mail or here…
    Thanks in advance

  10. theme Says:

    First of all,this post is awsome and i've learned great and useful things but, i wonder if there's any way to be able to work with matlab (playing sounds) and listening music with another program (f.i. firefox and streaming) without having to kill one of both.

  11. Kamil Says:

    Good question, lets try a few things… if I play music using mplayer and then use say play (a sox based playback script) to play another audio file. Both play fine.

    If I play music using mplayer and the start matlab and try to play any audio (even after mplayer finished) it fails like so:

    >> x=wavread('sp10.wav');
    Warning: The playback thread did not start within one second.
    > In audioplayer.playblocking at 35
    In audiovideo/private/playsnd at 16
    In sound at 46
    In soundsc at 48
    >> Unable to open the audio device for playback: javax.sound.sampled.LineUnavailableException: Audio Device Unavailable

    To get it to work, I have to quit matlab and start it again. On the other hand, if I start matlab first and then try to play audio using mplayer, then mplayer fails to play — it simply sits there with the following prompt: Starting playback…

    Ok, so as mentioned previously it is matlab's java based playback libs that simply requires exclusive access to the audio device. A bit of googling confirms that this is a common problem, and that java and/or alsa are at fault for not handling these things nicely.

    Alright, if I had to do it, then my hack would be as follows. I would create a matlab wrapper function file called play.m somewhere in matlab's path. The content of play.m would be something like this:

    % Saves audio data to a wav file before playback.
    % audio - audio samples
    % fs - sampling rate (Hz) [default: 8000]
    % nbits - precision (bits) [default: 16]
    % wavfile - filename for the wav file [default: '/tmp/tmp.wav']
    % usage: play(audio, fs, nbits, wavfile)

    function play(audio, fs, nbits, wavfile)

    % parse input arguments or use defaults
    case 1, wavfile='/tmp/tmp.wav'; nbits=16; fs=8000;
    case 2, wavfile='/tmp/tmp.wav'; nbits=16;
    case 3, wavfile='/tmp/tmp.wav';
    case 4,
    otherwise, error(sprintf('usage: play(audio, 8000, 16, "/tmp/tmp.wav"\ntype: help play for further details…'));

    % save audio to file, scale prior to writing to avoid clipping
    audio = 0.999*audio/max(abs(audio));
    wavwrite(audio, fs, nbits, wavfile);

    % playback the audio
    if(exist(wavfile, 'file'))
    syscmd = sprintf('mplayer %s', wavfile); % uses mplayer for playback
    %syscmd = sprintf('play %s', wavfile); % uses sox play for playback
    error(sprintf('%s: file not found.', wavfile));

    % EOF

    In matlab, help play gives the following:

    >> help play
    Saves audio data to a wav file before playback.

    audio - audio samples
    fs - sampling rate (Hz) [default: 8000]
    nbits - precision (bits) [default: 16]
    wavfile - filename for the wav file [default: '/tmp/tmp.wav']

    usage: play(audio, fs, nbits, wavfile)
    Overloaded methods:

    So make sure that your play.m is in the path before the other ones, or call it something else…

    Ok, it is not pretty, but it works.


  12. Dimitris Says:

    Any solution for me?

  13. Kamil Says:

    Hi Dimitris, in all likelihood your sound card can play and record at the same time, f.e. I can use, at the same time, mplayer for playback and gnome-sound-recorder for recording, without errors. The only thing that can get tricky are the mixer settings. Try un-muting all devices using alsamixer and set all the volumes to maximum to get started.

  14. theme Says:

    Kamil: completely agree with you, that is a so dirty solution, but as you point it works. The pitty is that Matlab/java and/or Alsa team doen't manage to fix it. Let's hope they get any solution. Linux is for work and have fun and multitasking system so, we should be able to do both, working with matlab while enjoying great music.

    Anyway thanks for the tip, i liked itvery much, sorry for the absence but i've been working in other issues, and now i've already focused again in matlab : )

    THNX again ;)

  15. Aistis Says:

    I luv this tutorial.. OneMegaThanksToYou !!!

  16. Charlie Says:

    This is a very well written article - I like that it comes with an explanation as well as the commands.

  17. portableRIOT Says:

    so… I'm having the same troubles, I'm attempting to video chat, and I finally got my webcam to work in unbuntu, but now my mic and sound aren't accessable by aMSN. I've tried your fix in the terminal, and It's not working. Could it be because I have an older version of linux, seriously updated? (I installed it on my windows laptop because windows kept crashing on me, and I have no other options.)


    and thanks :)

  18. Stasy Says:

    Thanks a lot!

  19. Suhrid Karthik Says:

    Great write up. Really Useful. Thanks.

  20. Gato Says:

    Thanks very much.

    Very good learning!

  21. Audio issues: What do I delete to make a clean start in alsa? Says:

    […] Read this…nd-device-p25/ […]

  22. Sander Says:

    Great how to! This showed me what my problem is.
    Unfortunately, I still can't solve it. Here is my problem:

    When in Matlab I play a sound, either with 'sound', 'soundsc' or another matlab function it plays it fine, but afterwards I cannot play any other sound. The error is the following:

    Unable to open the audio device for playback: javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 8192.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian not supported.

    I followed some this how to and discovered that matlab does not close the file used for writing the sound. Sometimes it closes eventually and sometimes I cannot listen to anything unless I close matlab first.
    When I execute the 'lsof | grep snd' command in a console I get the following output:

    gnome-set 1506 sander mem REG 8,5 409528 134483 /usr/lib/
    pulseaudi 1521 sander mem REG 8,5 409528 134483 /usr/lib/
    pulseaudi 1521 sander 28u CHR 116,8 0t0 7782 /dev/snd/controlC0
    pulseaudi 1521 sander 35u CHR 116,8 0t0 7782 /dev/snd/controlC0
    gconf-hel 1544 sander mem REG 8,5 409528 134483 /usr/lib/
    indicator 1635 sander mem REG 8,5 409528 134483 /usr/lib/
    firefox 2178 sander mem REG 8,5 409528 134483 /usr/lib/
    MATLAB 3704 sander mem REG 8,5 409528 134483 /usr/lib/
    MATLAB 3704 sander mem CHR 116,5 7777 /dev/snd/pcmC0D0p
    MATLAB 3704 sander 318u CHR 116,5 0t0 7777 /dev/snd/pcmC0D0p

    There are some other processes which have opened a/some sound filedescriptors (I don't fully understand it), but these did not prevent matlab from executing the sound the first time.

    So my question is: Does anyone know what is going on? Are these processes perhaps causing deadlock on the soundcard? Is there a way to forcefully close a filedescriptor or make a process release a resource? Or another more permanent solution?

    Any help would be very welcome.

  23. question Says:

    Well, article is well written indeed, but…
    i wish to have solution, that java program would work with gstreamer apllications simuntaneously.

    by default, ubuntu and gnome tend to provide pulseaudio. pulseaudio may be good idea in theory, but in practice pure alsa works better (doeas not glich).
    so i get rid pulse by removing it by default.
    but java issue remains.

    now question, how to setup linux sound in way, that there is provided hardware sound device + at least one virtual hardware device, mixer controls to playback sound from both, for simultaneous play (java program +some other program playback)

  24. question Says:

    yeah… and for getting answer, one must simply ask the question…
    mine was provided here:
    and, after following procedures - i ended up with working system sound from java based chess program and listen music from rhythmbox.

  25. Minna Says:

    I’m not that much of a online reader to be honest but your
    blogs really nice, keep it up! I'll go ahead and bookmark your website to come back later. All the best

Leave a Reply