SDL2音频问题C编程(不是混音器)

SDL2 audio issues C programming (not mixer)

我很难用 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时,不再播放声音。

我认为它与空时的缓冲区有关。不知道我误解了一些观点。

不允许我使用其他库。

我找到了

它可能会有所帮助: 在.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);
    }
}