使用SDL_mixer播放一个声音吗?

时间:2019-04-21 19:28:14

标签: c++ sdl sdl-mixer

我有4种声音。我需要播放声音1,播放完毕后会自动播放声音2;当声音2结束时,自动播放声音3。声音3结束时,播放声音4 ....我正在使用SDL Mixer 2.0,没有SDL声音...有办法吗?

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;

}

1 个答案:

答案 0 :(得分:1)

使用Mix_Playing()循环检查通道是否仍在播放,并使用SDL_Delay()添加延迟以防止循环消耗所有可用的CPU时间。

(在此示例中,我将您对Mix_PlayChannel()的第一次呼叫从-1更改为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.

您可能应该将其包装到一个函数中,这样您就不会一遍又一遍地重复基本相同的代码:

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);