c threads - why does mmsystem (using mciSendString) not play the sound file?

1k Views Asked by At

I want my game to play some sfx. At the beginning, I open some mp3 file mciSendString("open Muzle.mp3 alias Muzle");.

My problem is that mciSendString("play Muzle from 0"); still causes a little lag and the game has to play the sounds frequently.

In another question, I read that using threads will solve the problem. I'm completely new to using threads. The problem now is that the sound doesn't play :p . I verified that the thread runs properly by giving a cout at the end.

I have this function now:

void Shout(string SoundName){
    string FNstr;
    wstring FNwstr;
    FNstr = "play " + SoundName + " from 0";
    FNwstr.assign(FNstr.begin(), FNstr.end());
    mciSendString(FNwstr.c_str(), NULL, 0, NULL);
    Sleep(2000);
    cout << "Test woi\n";
}

(I tried without Sleep too. I wonder if I need it, because if the thread reaches the end, it might get deleted and the sound terminated... I'm not sure how threads or the mmsystem work)

If I simply call this Shout() function, it will play the sound, do the Sleep(2000), and then cout. Everything worked fine. But I have to use threads, so I try:

thread(Shout, "Muzle");

and I got error: abort() has been called. I figured out I may need to detach the thread:

thread t(Shout, "Muzle");
t.detach();

With this, everything looked to work fine (after 2 seconds, I see the "Test woi" printed on the console), but no sound was played.

Hmm, so thanks for reading everything ^.^ . Do you know how to solve this problem?

1

There are 1 best solutions below

2
On

You should probably have ONE permanent thread that: 1. Waits for the sound to finish before moving on (assuming that is the way you want it to work). You can probably just use the "wait" option to do that. 2. When not playing a sound, waits for a command to play the next sound - using a pipe to send messages to the thread would be one such solution, but you could use other methods.