Home > Back-end >  how to add a background sound in my program that does not stop until I close the console in c
how to add a background sound in my program that does not stop until I close the console in c

Time:12-01

The issue I'm facing is that the sound is not running in a loop, the whole sound is executed once, it does not repeat.

So basically, I have used this method:

#include <Windows.h>
#include <thread>
#include <iostream>

void play_music() {
    PlaySoundA("sound.wav", NULL, SND_FILENAME | SND_LOOP);
}

int main(){
    
 std::thread t(play_music); 
 //code
 t.join();
}

CodePudding user response:

From the documentation:

SND_LOOP

The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. If this flag is set, you must also set the SND_ASYNC flag.

CodePudding user response:

The SND_LOOP flag requires the SND_ASYNC flag, which means PlaySoundA() will exit immediately, and thus your thread will terminate, which will cause join() to exit, allowing main() to exit.

If you want to play the sound in a synchronous loop, then remove the SND_LOOP flag and call PlaySoundA() in a loop instead, eg:

#include <Windows.h>
#include <thread>
#include <iostream>
#include <atomic>

std::atomic_bool keep_playing{ true };

void play_music() {
    while (keep_playing.load()) {
        PlaySoundA("sound.wav", NULL, SND_FILENAME);
    }
}

int main(){  
  std::thread t(play_music); 
  //code
  keep_playing.store(false);
  t.join();
}

But in this case, you don't actually need the thread at all, just let SND_ASYNC to its job, eg:

#include <Windows.h>
#include <iostream>

int main(){  
  PlaySoundA("sound.wav", NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);
  //code
  PlaySoundA(NULL, NULL, 0);
}
  • Related