SDL音频回调没有声音

时间:2020-09-20 17:21:29

标签: c++ sdl

我试图获取一个简单的正弦波声音生成示例,该示例在Windows 10上使用SDL 2.0.12进行工作,但是没有声音输出。 我不知道这是否与代码,输出设备或音频驱动程序有关。 我非常感谢关于如何进一步调试问题的建议。

#include <iostream>
#include "SDL.h"


float sine_freq = 200.0f;
float audio_volume = 4000.0f;
float audio_frequency;

void SineAudioCallback(void* userdata, Uint8* stream, int len) {
    float* buf = (float*)stream;
    for (int i = 0; i < len / 4; ++i) {
        buf[i] = (float)(audio_volume * sin(2 * M_PI * i * audio_frequency));
    }
    return;
}

int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_AUDIO)) {
        return 1;
    }

    std::cout << "[SDL] Audio driver: " << SDL_GetCurrentAudioDriver() << std::endl;

    SDL_AudioSpec want, have;
    SDL_zero(want);

    want.freq = 5000;
    want.format = AUDIO_F32;
    want.channels = 2;
    want.samples = 4096;
    want.callback = SineAudioCallback;

    std::cout <<"[SDL] Desired - frequency: " << want.freq
        << ", format: f " << SDL_AUDIO_ISFLOAT(want.format)  << " s " << SDL_AUDIO_ISSIGNED(want.format) << " be " << SDL_AUDIO_ISBIGENDIAN(want.format) << " sz " << SDL_AUDIO_BITSIZE(want.format)
        << ", channels: " << (int)want.channels << ", samples: " << want.samples << std::endl;


    SDL_AudioDeviceID dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, SDL_AUDIO_ALLOW_ANY_CHANGE);

    if (!dev) {
        SDL_Quit();
        return 1;
    }


    std::cout << "[SDL] Desired - frequency: " << have.freq
        << ", format: f " << SDL_AUDIO_ISFLOAT(have.format) << " s " << SDL_AUDIO_ISSIGNED(have.format) << " be " << SDL_AUDIO_ISBIGENDIAN(have.format) << " sz " << SDL_AUDIO_BITSIZE(have.format)
        << ", channels: " << (int)have.channels << ", samples: " << have.samples << std::endl;

    audio_frequency = sine_freq / have.freq;

    SDL_PauseAudioDevice(dev, 0);
    SDL_Delay(10000);

    SDL_CloseAudioDevice(dev);
    SDL_Quit();

    return 0;
}

我得到的输出是

[SDL]音频驱动程序:wasapi

[SDL]期望-频率:5000,格式:f 256 s 32768为0 sz 32,通道:2,采样数:4096

[SDL]期望-频率:5000,格式:f 256 s 32768为0 sz 32,通道:2,采样率:118

因此,我想要的SDL_AudioSpec与要减少的样本数量有所不同。

我也收到与dll相关的错误消息,尽管不确定它是否重要。 avcore\audiocore\client\audioclient\audioclientcore.cpp(1839)\AUDIOSES.DLL!00007FFC48E00F8E: (caller: 0000000070D6BE39) ReturnHr(1) tid(46dc) 80070057 The parameter is incorrect.

1 个答案:

答案 0 :(得分:0)

事实证明,要解决此问题,我需要做两件事。

对于float类型,声波只能接受从-1到1的值,而我使用的音量要大得多。我需要改变

float audio_volume = 1.0f;

对于Windows,直接声音和winmm驱动程序提供的采样长度比wasapi好。对于Windows上的SDL2,需要将SDL_AUDIODRIVER=directsoundSDL_AUDIODRIVER=winmm设置为环境变量。 More details here