I struggle with playing sound in C.
here my function :
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);
}
}
The sound will play several times and then won't play again.
I check SDL_GetQueuedAudioSize, and when he is reaching 0, no more sound is playing.
I think its about buffer when is empty.. dunno i misunderstand some point.
I am not allowed to use another lib.
i found
it may help: in .h
typedef struct son_s {
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8 *wavBuffer;
SDL_AudioDeviceID deviceId;
}son_t;
if lot of sound, you make a structure array.
in .c file
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);
}
}