c ++中的背景音乐

时间:2013-11-10 21:33:19

标签: c++ winapi codeblocks

在c ++中播放wave文件时,程序不再执行任何其他操作。通常你必须等待轨道完成然后程序才会继续,但我正在播放循环轨道,我需要它在程序执行时播放。有没有办法做到这一点?感谢。

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

cout << "x1" << endl;
cin >> x1;

cout << "y1" << endl;
cin >> y1;

cout << "x2" << endl;
cin >> x2;

cout << "y2" << endl;
cin >> y2;

double f = slope (x1,y1,x2,y2);

cout << "y = " << m << "x + " << yi << endl;

2 个答案:

答案 0 :(得分:3)

根据documentation

SND_ASYNC   The sound is played asynchronously and PlaySound returns immediately
            after beginning the sound. To terminate an asynchronously played
            waveform sound, call PlaySound with pszSound set to NULL.

所以:

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

答案 1 :(得分:1)

正如Benjamin Lindley所写,API中有SND_ASYNC选项,我没有想到。或者你也可以玩线程。

如果您想在执行其他代码时继续播放音乐,则需要在不同的线程中开始播放音乐代码。您可以使用C++11个线程来完成它。

示例代码

#include <iostream>
#include <thread>

void play_music() {
  PlaySound("sleep_away.wav", NULL, SND_FILENAME|SND_LOOP);
}

int main(int argc, char* argv[])
{
  std::thread t(play_music);

  // other code

  t.join();

    return 0;
}