我正在尝试通过主音频回调函数在SDL中播放简单的方波。但是,尽管数据似乎已写入音频缓冲区,但我似乎无法播放任何音频。
但是,如果我加载.wav文件,则音频可以正常播放(将数据写入同一位置
在编写了自己的代码以尝试解决问题之后,我尝试了网上发现的许多正弦/方波。看来问题可能与波形无关,但是由于wav文件有效,因此我不确定还有什么可能导致问题:
#include "x:\SDL2-2.0.10\include\SDL.h"
#define INITIAL_SCREEN_WIDTH (8*80)
#define INITIAL_SCREEN_HEIGHT (8*60)
typedef struct audio_user_data audio_user_data;
struct audio_user_data
{
int SamplesPerSecond;
int BytesPerSample;
int SampleIndex;
int ToneHz;
int ToneVolume;
int WavePeriod;
Uint32 FileLength;
Uint16* BufferLocation;
};
void
AudioCallback(void* UserData, Uint8* Stream, int Length)
{
audio_user_data* AudioUserData = (audio_user_data*)UserData;
static Uint32 Count = 0;
Sint16* SampleBuffer = (Sint16*)Stream;
int SamplesToWrite = Length / AudioUserData->BytesPerSample;
for(int SampleIndex = 0; SampleIndex < SamplesToWrite; SampleIndex++)
{
Sint16 SampleValue = ((Count++ / (AudioUserData->WavePeriod/2)) % 2) ? AudioUserData->ToneVolume : -AudioUserData->ToneVolume;
*SampleBuffer++ = SampleValue;
*SampleBuffer++ = SampleValue;
}
}
int
main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
SDL_Window* Window = SDL_CreateWindow("Spell Checker", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, INITIAL_SCREEN_WIDTH*2, INITIAL_SCREEN_HEIGHT*2, 0);
SDL_Renderer* Renderer = SDL_CreateRenderer(Window, 0, SDL_RENDERER_SOFTWARE);
SDL_PixelFormat* Format = SDL_AllocFormat(SDL_PIXELFORMAT_RGB888);
SDL_Texture* Screen = SDL_CreateTexture(Renderer, Format->format, SDL_TEXTUREACCESS_STREAMING, INITIAL_SCREEN_WIDTH, INITIAL_SCREEN_HEIGHT);
audio_user_data AudioUserData = {0};
AudioUserData.SamplesPerSecond = 48000;//44100;
AudioUserData.BytesPerSample = 2 * sizeof(Sint16);
AudioUserData.SampleIndex = 0;
AudioUserData.ToneVolume = 5000;
AudioUserData.ToneHz = 256;
AudioUserData.WavePeriod = AudioUserData.SamplesPerSecond / AudioUserData.ToneHz;
SDL_AudioSpec Want, Have;
SDL_AudioDeviceID AudioDeviceID;
Want.freq = 48000; // 44100;
Want.format = AUDIO_S16;
Want.channels = 2;
Want.samples = 4096;
Want.callback = &AudioCallback;
Want.userdata = &AudioUserData;
AudioDeviceID = SDL_OpenAudioDevice(0, 0, &Want, &Have, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDL_PauseAudioDevice(AudioDeviceID, 0); // Start playing
Uint32* PixelMap = calloc(INITIAL_SCREEN_WIDTH * INITIAL_SCREEN_HEIGHT, sizeof(PixelMap));
int PixelMapLocation = 0;
int Running = 1;
while(Running)
{
SDL_Event Event;
while(SDL_PollEvent(&Event))
{
if(Event.type == SDL_QUIT)
{
Running = 0;
break;
}
}
// Test colors
PixelMapLocation = 0;
for(int Row = 0; Row < INITIAL_SCREEN_WIDTH; ++Row)
{
for(int Col = 0; Col < INITIAL_SCREEN_HEIGHT; ++Col)
{
PixelMap[PixelMapLocation++] = 0xFF00FF;
}
}
for(int Row = 0; Row < INITIAL_SCREEN_WIDTH; ++Row)
{
for(int Col = 0; Col < INITIAL_SCREEN_HEIGHT; ++Col)
{
PixelMap[PixelMapLocation++] = 0x00FFFF;
}
}
SDL_UpdateTexture(Screen, 0, PixelMap, INITIAL_SCREEN_WIDTH * sizeof(PixelMap));
SDL_RenderClear(Renderer);
SDL_RenderCopy(Renderer, Screen, 0, 0);
SDL_RenderPresent(Renderer);
}
return(0);
}