问题
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.
回答1:
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.
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.
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.
回答2:
Unless you specify the SND_ASYNC
flag, the PlaySound function is synchronous, meaning that after you call it, it does not return control to your program until after it has finished playing the sound file.
Therefore, once the function returns a value (either TRUE
if successful, or FALSE
otherwise), you know that the sound has finished playing.
You can simply update the text of your button control in the next line of code, immediately after you call the PlaySound
function. If you want to ensure that the button gets updated immediately to reflect your changes, you might need to call the UpdateWindow function, as well.
来源:https://stackoverflow.com/questions/5934059/how-do-i-detect-when-the-sound-has-finished-playing-when-using-playsound-in-win3