简体   繁体   English

C++:SDL 音频回调最终停止工作

[英]C++: SDL audio callback eventually stops working

I'm making an audio visualizer with, among others, SDL to record audio.我正在制作一个音频可视化器,其中包括 SDL 来录制音频。

When I turn on audio recording, everything works fine for anywhere between 0 and 20 seconds, and then SDL stops making audio callbacks.当我打开录音时,在 0 到 20 秒之间一切正常,然后 SDL 停止进行音频回调。 I'm under the impression that this happens when there isn't any sound for a short period of time, but no matter how much noise I make, I can't prevent it.我的印象是,当短时间内没有任何声音时会发生这种情况,但无论我发出多少噪音,我都无法阻止它。

Here is an outline of my code.这是我的代码的大纲。 There is a lot of it, so I'll omit things I think are working properly.有很多,所以我会省略我认为正常工作的东西。

//(imports and stuff)
bool active = false;
Uint8* rawSamples = nullptr;
float* audioBuffer = nullptr;

int main() {
   init();
   active = true;
   while (active) {
       float* audio = getAudio();
       handleEvents();
   }

}

void init () {
    // (SDL Init, device selection, device opening)
    // dev: device ID returned by SDL_OpenAudioDevice, have: audioSpec of said device

    int rawSamplesSize = (int)have.samples * SDL_AUDIO_BITSIZE(have.format) * have.channels / 8;
    rawSamples = new Uint8[rawSamplesSize * 4];
    audioBuffer = new float[(int)have.samples];

    SDL_PauseAudioDevice(dev, 0);
}

void audioCallback(void* userdata, Uint8* stream, int len) {
    for (int i = 0; i < len; i++) {
        rawSamples[i] = stream[i];
    }
}

float* getAudio() {
    SDL_LockAudioDevice(dev);
    for (int i = 0; i < have.samples; i++) {
        audioBuffer[i] = ((float*)rawSamples)[i];
    }
    *audioLengthPointer = have.samples;
    SDL_UnlockAudioDevice(dev);
    return audioBuffer
}

void handleEvents() {
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
        if (e.type == SDL_QUIT) {
            active = false;
        }
    }
}

I have checked a few things: The recording works properly.我检查了几件事: 录音工作正常。 The device stays active even when there aren't any callbacks.即使没有任何回调,设备也会保持活动状态。 It isn't a locking-unlocking problem.这不是锁定-解锁问题。 Pausing-Unpausing doesn't seem to help.暂停-取消暂停似乎没有帮助。 The program keeps going, even without callbacks.即使没有回调,程序也会继续运行。 At the start, there are a few callbacks without any getAudio calls between them.一开始,有一些回调,它们之间没有任何 getAudio 调用。

Note: I already know this question is similar to SDL audio callback stops after two iterations but in my case I am recording audio, and the number of callbacks isn't fixed.注意:我已经知道这个问题类似于SDL 音频回调在两次迭代后停止,但在我的情况下,我正在录制音频,并且回调的数量不固定。

Changing drivers has solved the problem.更换驱动程序解决了这个问题。 Since the question now becomes why wasapi decides to stop sending audio data, which isn't quite related to SDL, I'm closing this question.由于现在的问题变成了为什么 wasapi 决定停止发送与 SDL 不太相关的音频数据,我将结束这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM