Hi there,
I made a simple test program to output audio, by using callback function, but despite the callback function being called , there is no sound out of the speakers.
Im using sdl2 on windows computer.
I only have 1 output device (realtek (R) audio )
The code should output a noise sound, see for yourself
Here is the code:
using namespace std;
SDL_AudioSpec want, have;
SDL_AudioDeviceID player;
void SDLCALL callback_player( void* userdata, Uint8* stream, int len){
for (int i = 0; i < len; i ++) {
auto value = Uint8(sin(i) * 10000);
stream[i] = value ;
}
}
auto setupAudioPlayer() {
printf("### Device Player ###\n");
int num = SDL_GetNumAudioDevices(false);
printf("num: %d\n", num);
for (int i = 0; i < num; i++) {
auto name = SDL_GetAudioDeviceName(i, false);
printf("%d: %s\n", i, name);
}
int deviceIndex;
printf("select device to player audio: ");
scanf_s("%d", &deviceIndex);
printf("\n");
SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */
want.freq = 44100;
want.format = AUDIO_F32;
want.channels = 2;
want.samples = 1024;
want.callback = callback_player; // you wrote this function elsewhere.
//want.size = 512;
SDL_AudioDeviceID player = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(deviceIndex, false), SDL_FALSE, &want, &have, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
if (player == 0) {
printf("Failed to open player device! SDL Error: %s", SDL_GetError());
}
else {
printf("freq %d \nformat %d \nchannels %d \nsamples %d\n", have.freq, have.format, have.channels, have.samples);
}
return player;
}
void destroyAudio() {
SDL_CloseAudioDevice(player);
SDL_Quit();
}
int main(int n , char**args) {
int err = SDL_Init(SDL_INIT_AUDIO);
printf("error: %d", err);
if (err < 0) {
printf("erorr: %d\n", err);
printf("Failed to init audio! SDL Error: %s", SDL_GetError());
}
//recorder = setupAudioRecorder();
auto player = setupAudioPlayer();
printf("player: %d\n", player);
//loadWave();
printf("playing\n");
//SDL_PauseAudioDevice(recorder, 0);
SDL_PauseAudioDevice(player, 0);
//SDL_SemWait(sem);
SDL_Delay(10000);
destroyAudio();
//system("pause");
return 0;
}
Can someone please tell me what is wrong with this code, and if its nothing wrong with it , do you have any idea why audio is not outputing from the speakrs.
Thanks !!