我很难在C语言中播放声音。
这是我的功能:
void playSound(char* path)
{
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8 *wavBuffer;
SDL_LoadWAV(path, &wavSpec, &wavBuffer, &wavLength);
SDL_AudioDeviceID deviceId = SDL_OpenAudioDevice(NULL, 0, &wavSpec, NULL, 0);
SDL_QueueAudio(deviceId, wavBuffer, wavLength);
SDL_PauseAudioDevice(deviceId, 0);
if (SDL_GetQueuedAudioSize(deviceId) == 0) {
SDL_CloseAudioDevice(deviceId);
SDL_FreeWAV(wavBuffer);
}
}
声音将播放几次,然后不再播放。
我检查SDL_GetQueuedAudioSize,当他达到0时,不再播放声音。
我认为它是关于缓冲区何时为空的。.dunno我误解了一点。
不允许我使用另一个库。
答案 0 :(得分:0)
我发现了
它可能会帮助: 在.h
typedef struct son_s {
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8 *wavBuffer;
SDL_AudioDeviceID deviceId;
}son_t;
如果声音很大,您可以制作一个结构数组。
.c文件中的
void closeAudio(son_t* son)
{
SDL_CloseAudioDevice(son->deviceId);
}
son_t* initAudio(char* path)
{
son_t* son = malloc(sizeof(son_t));
if (!son) {
return NULL ;
}
SDL_LoadWAV(path, &son->wavSpec, &son->wavBuffer, &son->wavLength);
son->deviceId = SDL_OpenAudioDevice(NULL, 0, &son->wavSpec, NULL, 0);
return son;
}
void playSound(son_t* son)
{
SDL_QueueAudio(son->deviceId, son->wavBuffer, son->wavLength);
SDL_PauseAudioDevice(son->deviceId, 0);
if (SDL_GetQueuedAudioSize(son->deviceId) == 0) {
SDL_FreeWAV(son->wavBuffer);
}
}