3

I have 4 sounds. I need play sound 1, when it finishes, automatically play sound 2; when sound 2 finishes, automatically play sound 3. Soun 3 finishes, play sound 4.... I'm using SDL Mixer 2.0, no SDL Sound...Is there a way?

int main() {
    int frequencia = 22050;
    Uint16 formato = AUDIO_S16SYS;
    int canal = 2; // 1 mono; 2 = stereo;
    int buffer = 4096;
    Mix_OpenAudio(frequencia, formato, canal, buffer);

    Mix_Chunk* sound_1;
    Mix_Chunk* sound_2;
    Mix_Chunk* sound_3;
    Mix_Chunk* sound_4;

    som_1 = Mix_LoadWAV("D:\\sound1.wav");
    som_2 = Mix_LoadWAV("D:\\sound1.wav");
    som_3 = Mix_LoadWAV("D:\\sound1.wav");
    som_4 = Mix_LoadWAV("D:\\sound1.wav");

    Mix_PlayChannel(-1, sound_1, 0);
    Mix_PlayChannel(1, sound_2, 0);
    Mix_PlayChannel(2, sound_3, 0);
    Mix_PlayChannel(3, sound_4, 0);

    return 0;

}
genpfault
  • 51,148
  • 11
  • 85
  • 139
mrsoliver
  • 91
  • 2
  • 8

1 Answers1

5

Check in a loop whether the channel is still playing using Mix_Playing(), and add a delay using SDL_Delay() to prevent the loop from consuming all available CPU time.

(In this example, I changed your first call to Mix_PlayChannel() from -1 to 1.)

Mix_PlayChannel(1, sound_1, 0);
while (Mix_Playing(1) != 0) {
    SDL_Delay(200); // wait 200 milliseconds
}

Mix_PlayChannel(2, sound_2, 0);
while (Mix_Playing(2) != 0) {
    SDL_Delay(200); // wait 200 milliseconds
}

// etc.

You should probably wrap that into a function instead so that you don't repeat what is basically the same code over and over again:

void PlayAndWait(int channel, Mix_Chunk* chunk, int loops)
{
    channel = Mix_PlayChannel(channel, chunk, loops);
    if (channel < 0) {
        return; // error
    }
    while (Mix_Playing(channel) != 0) {
        SDL_Delay(200);
    }
}

// ...

PlayAndWait(-1, sound_1, 0);
PlayAndWait(1, sound_2, 0);
PlayAndWait(2, sound_3, 0);
PlayAndWait(3, sound_3, 0);
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • almost works fine... setting delay in 0, even so, there are a small silence between sound 1 and 2... i need the sound 2 play imediatly after sound 1, whitout latency... – mrsoliver Apr 21 '19 at 21:35
  • @mrsoliver I don't know if SDL_mixer can do gapless playback. – Nikos C. Apr 21 '19 at 23:14