Why call PlaySound(NULL, NULL, SND_NODEFAULT)?

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

 PlaySound(NULL, NULL, SND_NODEFAULT);
PlaySound(".Default", NULL, SND_SYSTEM | SND_ASYNC | SND_NODEFAULT);

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.