Search code examples
cwindowswinapiplaysound

How do I detect when the sound has finished playing when using PlaySound in Win32 SDK?


I am using the PlaySound function from the Win32 SDK to play a wave sound file. Currently, I have the following line of code:

PlaySound(szFile,NULL,SND_FILENAME );

But now I want to know, how I can detect the time when the wave file finished playing? I want to change a button's text when the wave stops playing.


Solution

  • PlaySound is very limited in what it can do. In a product I work on, we built a media playback library on top of DirectSound to do get over the limitations. Among many things it did, it involved writing a WAV file parser and threading code to maintain a stream of PCM samples into a DirectSound buffer. Not for the faint of heart.

    You could go this route, but here's some simpler suggestions.

    1. If you know the length of the WAV file you are playing, you can call PlaySound with the SND_ASYNC flag. Schedule a timer to fire at the estimated time the sound is supposed to finish playing. If you don't know the length of the WAV file, you could write a parser to read the header of the file. Compares the sampling rate and format from the "fmt" chunk to the number of bytes in the data chunk to compute the time length of the file.

    2. OR.... Create a dedicated thread for issuing PlaySound calls (without the SND_ASYNC flag). When the synchronous PlaySound function returns, do a PostMessage to your UI thread to update the button. If you have overlapping calls to PlaySound, you'll likely need to do some multi-threaded synchronization, but it shouldn't be hard.