My code isn’t working. I think I’ve done everything correctly according to the official SDL2 documentation. It should play a sinewave for just under 1 second, but instead I hear nothing. The strange thing is that I have error checks at a couple places and it should pop up an error message box if anything is going wrong. But I don’t get any error messages. It’s like it’s failing in a way that it shouldn’t, and so isn’t actually triggering the official error catching routines that enable the operation of the SDL_GetError function.
I’ve completely documented my code so you can see what each piece of code is supposed to be doing. Below is the complete code for my program. Please tell me what’s wrong with my program.
#include <smallcrt.h>
#include <stdlib.h>
#include <SDL.h>
#include <windows.h>
void _start(){
SDL_AudioSpec as;
SDL_AudioSpec as2;
SDL_AudioDeviceID ad;
short buff[4096];
int n;
//configure desired audio output spec
as.freq = 48000;
as.format = AUDIO_S16LSB;
as.channels = 1;
as.samples = 4096;
as.callback = 0; //no callback
as.silence = 0; //field will be initialized by SDL_OpenAudioDevice, but must be set to 0 now
as.size = 0; //field will be initialized by SDL_OpenAudioDevice, but must be set to 0 now
as.userdata = 0; //set this to zero as no callback will be used so user defined data for callback is unneeded
//zero all fields for actual audio output spec struct in preparation for SDL_OpenAudioDevice to fill it with meaningful data
as2.freq = 0;
as2.format = 0;
as2.channels = 0;
as2.samples = 0;
as2.callback = 0;
as2.silence = 0;
as2.size = 0;
as2.userdata = 0;
for (n=0;n<4096;n++){
buff[n] = sin(3.14159*2*n*1000/48000)*0x7FFF; //create a 1khz sinewave at max amplitude to put into the buffer
}
SDL_Init(SDL_INIT_AUDIO); //initialize SDL audio sysetm
ad = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(1,0),0,&as,&as2,0); //open Headphones audio device
if (ad==0){
MessageBoxA(0,SDL_GetError(),"Error",0); //display error message if device doesn't open
}
SDL_PauseAudioDevice(ad,0); //activate device, so that it plays silence until audio data is queued later
//queue the 1khz sinewave audio data 10 times, which should play for just under 1 second
if (SDL_QueueAudio(ad,&buff,4096*2)){
MessageBoxA(0,SDL_GetError(),"Error",0); //first time check if it actually queued it without error, and display error message if it failed
}
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_QueueAudio(ad,&buff,4096*2);
SDL_Delay(2000); //delay closing of main thread, so that program won't end before SDL audio thread finishes playing queued sinewave
SDL_CloseAudioDevice(ad); //close the Headphones audio device
SDL_Quit(); //close SDL systems
ExitProcess(0); //quit program
}