我正在尝试使用SDL捕获音频流,然后将其传递给kissfft以确定哪个频率是信号中最主要的频率。但是,无论传入音频是什么信号,我总是得到3986作为最主要正弦波在fft中的位置。我知道我实际上收到了音频信号,因为更改信号时可以看到音量变化(我正在使用键盘生成音频信号)
#include "SDL.h"
#include "kiss_fftr.h"
#include <stdlib.h>
#define NUM_SAMPLES 4096
#define INPUT_DEVICE "Built-in Audio Analog Stereo"
volatile kiss_fftr_cfg kiss_cfg;
volatile int audio_count=0;
//This is what takes each audio sample and process it as an FFT
void AudioCallback(void* userdata, uint8_t *stream, int len1){
int audioVal =0;
kiss_fft_scalar in[NUM_SAMPLES];
int maxSamp =0, minSamp =0;
for(int i=0; i<len1; i++){`enter code here`
int val = (int8_t)stream[i];
maxSamp = (maxSamp < val) ? val :maxSamp;
minSamp = (minSamp < val)? minSamp : val;
int thisVal = stream[i] -128;
if(thisVal < 0)
thisVal = -1 * thisVal;
audioVal += thisVal;
in[i] = thisVal;
}
kiss_fft_cpx out[NUM_SAMPLES];
kiss_fftr(kiss_cfg, in, out);
long long int max = 0;
int maxPos = -1;
for(int i=0; i<NUM_SAMPLES; i++){
unsigned int thisVal = abs(out[i].r);
if(max <= thisVal){
maxPos = i;
max=thisVal;
}
}
printf("Max pos %7d, max val %15d audioval %15d| samples %d, %d %d %d\n", maxPos, max, audioVal, len1, NUM_SAMPLES, maxSamp, minSamp);
audio_count++;
}
//In here I both set up kissfft and SDL
int main(int argc, char* argv[]){
SDL_Init(SDL_INIT_AUDIO);
int i, count = SDL_GetNumAudioDevices(0);
printf("Found %d audio devices \n", count);
if(0 > count){
printf("Got this error %s\n", SDL_GetError());
}
for (i = 0; i < count; ++i) {
printf("Audio device %d: %s\n", i, SDL_GetAudioDeviceName(i, 0));
}
kiss_cfg = kiss_fftr_alloc(NUM_SAMPLES, 0, NULL, NULL);
SDL_AudioSpec want, have;
SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */
want.freq = 48000;
want.format = AUDIO_U8;
want.channels = 1;
want.samples = NUM_SAMPLES;
want.callback = AudioCallback;
SDL_AudioDeviceID devId = SDL_OpenAudioDevice(INPUT_DEVICE, 1, &want, &have, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
if(0 == devId)
{
printf("Failed to open %s\n", INPUT_DEVICE);
exit(1);
}
//SDL_LockAudioDevice(devId);
SDL_PauseAudioDevice(devId, 0);
while(1){
SDL_Delay(10);
}
SDL_UnlockAudioDevice(devId);
SDL_CloseAudioDevice(devId);
}
我希望maxpos会随着我在键盘上按的键的变化而变化,但是我总是得到“ Max pos 3986”。