SDL2音频问题C编程(不是调音台)

问题描述 投票:0回答:1

我在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时,不再播放声音了。

我认为它关于什么时候缓冲空..不知道我误解了一点。

我不被允许使用另一个lib。

c audio sdl sdl-2
1个回答
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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.