How to use PlaySound in C?

use PlaySound() in C++/OpenGL to play sound in background

  • I am trying to play a wav file in the background of a game built in c++ with opengl. I am using the following line to play the wav file: PlaySound("starwars.wav", NULL, SND_FILENAME|SND_LOOP); The problem is when the music starts the animation stops. I tried starting the music at the press of a keyboard button, but when I do that the music starts and the all the animation stops. Is there a way to avoid this? I just want some music to play in the background and PlaySound seemed the simplest way to achieve that, given the fact it requires just a line of code.

  • Answer:

    You want to pass in SND_ASYNC This would make PlaySound return immediately, rather than waiting for the sound to finish playing, which in your case wouldn't as you are looping. IIRC PlaySound only allows one sound to play at any one time so it may be best to look for a sound library, especially if you are making a game. In conclusion for your sample to work: PlaySound("starwars.wav", NULL, SND_ASYNC|SND_FILENAME|SND_LOOP); http://msdn.microsoft.com/en-us/library/windows/desktop/dd743680%28v=vs.85%29.aspx

biggdman at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

I'm no expert with the windows sound API, but it seems like the function PlaySound is a blocking operation, which means your application freezes until the function is finished, i.e the sound is played until the end. Maybe there is a flag to circumvent this? You could start a thread for the sound, which finishes after the sound has stopped. Or you might want to look into a simple sound API.

Constantinius

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.