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

I am trying to play a wav file against a background of a game built in C ++ with opengl. I use the following line to play the wav file:

PlaySound("starwars.wav", NULL, SND_FILENAME|SND_LOOP); 

The problem is that the music starts stopping the animation. I tried to start the music when I pressed the keyboard button, but when I do this, the music starts and the whole animation stops. Is there any way to avoid this? I just want some kind of music to play in the background, and PlaySound seemed the easiest way to achieve this, given the fact that it only needs a line of code.

+4
source share
3 answers

Do you want to pass

SND_ASYNC

This will make PlaySound return immediately, instead of waiting for the sound to finish the game, which in your case will not, because you are looping. IIRC PlaySound allows you to play only one sound at a time, so it's best to look for a sound library, especially if you're making a game.

In conclusion, for your sample to work:

PlaySound("starwars.wav", NULL, SND_ASYNC|SND_FILENAME|SND_LOOP);

See this

+6
source

I'm not an expert on the Windows Sounds API, but it looks like the PlaySound function is a blocking operation, which means your application freezes until the function completes, i.e. sound is played to the end. Maybe there is a flag to get around this?

You can start a stream for sound that ends after the sound stops. Or you can look at a simple API.

+1
source

If you use the playSound format ("*. Wav", NULL, SND_SYNC | SND_LOOP), you have almost no control over the animation of the game, which will be frozen using the loop included in the playSound () function, which is SND_LOOP, but if you change SND_SYNC to SND_ASYNC, it will work exactly the same as you ordered, but do not forget that it works for Windows and do not forget to include WINMM.LIB (window multimedia library) in the project / opengl / visual C ++ / link

+1
source

Source: https://habr.com/ru/post/1390245/


All Articles