我根据a github code制作了这个简单的程序。 所有你必须要处理的是main()方法结束时的while循环。
#include "SDL2\SDL.h"
constexpr const char* WAV_PATH = "applause.wav";
#include <iostream>
static Uint8* sg_pAudioPos;
static Uint32 sg_AudioLength;
struct CWavWrapper
{
Uint32 m_Length;
Uint8* m_pBuffer;
SDL_AudioSpec m_Spec;
};
void ExitProgram(int code = 0)
{
system("pause");
exit(code);
}
void AudioCallback(void* pData, Uint8* pStream, int Length);
#undef main
int main()
{
using std::cout;
using std::cerr;
using std::endl;
if (SDL_Init(SDL_INIT_AUDIO) < 0)
{
cerr << "couldnt init audio: " << SDL_GetError() << endl;
ExitProgram(1);
}
cout << "Loading wav... " << WAV_PATH << endl;
static CWavWrapper Wav;
if(SDL_LoadWAV(WAV_PATH,&Wav.m_Spec,&Wav.m_pBuffer,&Wav.m_Length) == NULL)
{
cerr << "couldnt load wav: " << SDL_GetError() << endl;
ExitProgram(1);
}
Wav.m_Spec.callback = AudioCallback;
Wav.m_Spec.userdata = NULL;
sg_pAudioPos = Wav.m_pBuffer;
sg_AudioLength = Wav.m_Length;
cout << "Opening Audio..." << endl;
if (SDL_OpenAudio(&Wav.m_Spec, NULL) < 0)
{
cerr << "couldn't open audio: " << SDL_GetError() << endl;
ExitProgram(1);
}
cout << "Success! Starting Audio..." << endl;
SDL_PauseAudio(0);
while (sg_AudioLength > 0)
{
//If I remove this output line or as in the GitHub example not do the SDL_Delay() the wav gets played infinitely.
//how does printing out a variable change its value (as it should do only in the callback)?
cout << "sg_AudioLength: " << sg_AudioLength << endl;
}
SDL_CloseAudio();
SDL_FreeWAV(Wav.m_pBuffer);
ExitProgram(0);
}
void AudioCallback(void* pData, Uint8* pStream, int Length)
{
if (sg_AudioLength == 0)
return;
if (Length > sg_AudioLength)
{
Length = sg_AudioLength;
}
SDL_MixAudio(pStream, sg_pAudioPos, Length, SDL_MIX_MAXVOLUME);
sg_pAudioPos += Length;
sg_AudioLength -= Length;
}
正如你在main()函数的末尾看到的那样,我描述了当我删除cout行时会发生什么。 我认为只有在某个代码完成时才调用AudioCallback可能需要做些什么。但我不确定,我想得到答案。
编辑:我注意到,当在while循环中处理任何内容时,音频似乎正常播放。从编译到运行时的任何事情都注意到循环没有改变变量并且认为这现在是无限循环所以循环甚至不尝试再次检查变量?