Why call PlaySound(NULL, NULL, SND_NODEFAULT)?

Someone just wandered over to my office and he had noticed the following pattern in his code:


He was wondering why on earth the code would do that call to PlaySound(NULL). 

As I explained it to him, the reason is because you almost always want to cancel the current sound playing before you queue up the next sound.

The problem is that the current implementation[1] of PlaySound(…, SND_ASYNC) simply queues the request to a worker thread which blocks waiting on the currently playing sound to complete.  So if you have a situation where you call PlaySound(…, SND_ASYNC) many times in succession, you’ll find that all the calls to PlaySound pile up behind each other, which means that you might end up playing sounds long after the action associated with the sound has completed.

Of course you might want this behavior – it’s certainly possible to string lots of system sounds together to produce any number of interesting effects.

But most of the time you just want to stop the current sound before you start playing the next.



[1] There are obviously no guarantees that the implementation of PlaySound won’t change – I’m just describing what the current code does.  Even if the implementation is changed, it won’t change the underlying behavior.

Comments (5)

  1. Nargal says:

    Is it just my imagination, or does Windows play the shutdown sound synchronously for the reason above?

    When I used one of the new Vista Ultimate sound schemes, I found the whole computer seemed to pause the logoff process while the sound gradually, gradually faded to nothing. Then the disk kicked in again and shutdown continued.

    Needless to say, I got rid of that sound scheme quicksmart (I think it might have been the one that sounds like someone’s moving a statue on concrete, half a second after you’ve minimized a window).

  2. Narr says:

    >But most of the time you just want to stop the current sound before you start playing the next.

    What if you want to play the sound immediately, but without introducing any consequences for other playing sounds?

  3. Nargal: Actually the shutdown sound is played synchronously for slightly different – but the rest of shutdown should proceed while it is playing.

    Narr: The semantics of PlaySound is that only one PlaySound call is active in a given process.  If you want different semantics, you need to use a different API :(.  Sorry about that.

  4. Mitchel Tyrell says:

    How would a stop an application (that I do not own) from playing any sounds. I would really like to write an extension for IE that would block all sounds from playing, especially from flash.

  5. You can’t, in general.  We don’t allow one application to control another application’s sounds (except for sndvol).

Skip to main content