[英]how to add a background sound in my program that does not stop until I close the console in c++
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();
}
From the documentation:从文档中:
SND_LOOP
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.
声音重复播放,直到再次调用 PlaySound 并将 pszSound 参数设置为 NULL。如果设置了此标志,则还必须设置 SND_ASYNC 标志。
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. SND_LOOP
标志需要SND_ASYNC
标志,这意味着PlaySoundA()
将立即退出,因此您的线程将终止,这将导致join()
退出,从而允许main()
退出。
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:如果您想在同步循环中播放声音,请移除
SND_LOOP
标志并改为在循环中调用PlaySoundA()
,例如:
#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:但是在这种情况下,您实际上根本不需要线程,只需让
SND_ASYNC
完成它的工作即可,例如:
#include <Windows.h>
#include <iostream>
int main(){
PlaySoundA("sound.wav", NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);
//code
PlaySoundA(NULL, NULL, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.