##本文旨在记录使用SDL(Simple DirectMedia Layer)播放Audio中遇到的问题
- SDL2库使用SDL_OpenAudioDevice播放不成功,使用SDL_OpenAudio播放成功,如下代码所示
//使用SDL_OpenAudioDevice进行播放
dev = SDL_OpenAudioDevice(NULL, 0, &wanted_spec, NULL, SDL_AUDIO_ALLOW_ANY_CHANGE);
if (dev == 0){
fprintf(stderr, "\nFailed to open audio: %s\n", SDL_GetError());
return -1;
}
//使用SDL_OpenAudio进行播放
if (SDL_OpenAudio(&wanted_spec, NULL) < 0){
fprintf(stderr, "\nFailed to open audio: %s\n", SDL_GetError());
return -1;
}
通过查阅SDL_OpenAudioDevice的 API文档,可以发现一下的描述:
For compatibility with SDL 1.2, this will never return 1, since SDL reserves that ID for the legacy SDL_OpenAudio() function.
通过查看SDL2的源代码,如下:
int
SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
{
SDL_AudioDeviceID id = 0;
/* Start up the audio driver, if necessary. This is legacy behaviour! */
if (!SDL_WasInit(SDL_INIT_AUDIO)) {
if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
return (-1);
}
}
/* SDL_OpenAudio() is legacy and can only act on Device ID #1. */
if (open_devices[0] != NULL) {
SDL_SetError("Audio device is already opened");
return (-1);
}
if (obtained) {
id = open_audio_device(NULL, 0, desired, obtained,
SDL_AUDIO_ALLOW_ANY_CHANGE, 1);
} else {
id = open_audio_device(NULL, 0, desired, desired, 0, 1);
}
SDL_assert((id == 0) || (id == 1));
return ((id == 0) ? -1 : 0);
}
SDL_AudioDeviceID
SDL_OpenAudioDevice(const char *device, int iscapture,
const SDL_AudioSpec * desired, SDL_AudioSpec * obtained,