1.https://www.cppgamedev.top/courses/sdl-space-shooter/parts/sdl-fundamentals
练习3:添加音效播放功能(使用Mix_LoadWAV和Mix_PlayChannel函数)
1.SDL使用的音频数据结构
chunk
- 完全预先加载进内存的文件
music - 一个根据需要(流式)解码的文件
2.使用到的函数
int Mix_PlayChannel(int channel, Mix_Chunk *chunk, int loops);
- 用途:Play an audio chunk on a specific channel.
- 如果指定channel为-1,则在第一个空闲的channel上播放
- 如果
loops
大于零,则循环声音多次。如果loops
为-1,则“无限”循环(约65000次)。
Mix_Chunk * Mix_LoadWAV(const char *file);
- 用途:Load a supported audio format into a chunk.
3.实现播放音效
// 读取音效
Mix_Chunk* sound = Mix_LoadWAV(getAssetPath("sound/eff5.wav").c_str());
if (!sound) {std::cerr << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl;return 1;
}
// 播放音效
Mix_PlayChannel(-1, sound, 100);
...
while(true) {...} //渲染循环
...
// 清理音乐资源
Mix_FreeChunk(sound);
...