So, I’ve been trying to add audio in my SDL 2 game development and the audio just isn’t working in SDL 2 the program constantly keeps crashing. Is there some sort of lib that I’ve forgot to add in?
In case your wondering Yes, this is C dev.
Here’s the code:
Call back function:
void MyAudioCallback( void *udata, Uint8 *stream, int len )
{
SDL_AudioFormat deviceFormat ;
Uint8 mixData ;
SDL_memset( stream, 0, len ) ;
/ Mix our audio against the silence, at 50% volume. */
SDL_MixAudioFormat( stream, mixData, deviceFormat, len, SDL_MIX_MAXVOLUME / 2 ) ;
}
Here’s a bit of what’s in main:
for( i = 0 ; i < SDL_GetNumAudioDrivers() ; ++i )
{
const char *driver_name = SDL_GetAudioDriver( i ) ;
if( SDL_AudioInit( driver_name ) )
{
printf( “Audio driver failed to initialize: %s\n”, driver_name ) ;
continue ;
}
SDL_AudioQuit( ) ;
}
/* Load the WAV */
if( SDL_LoadWAV( "test.wav", &wav_spec, &wav_buffer, &wav_length ) == NULL )
{
fprintf( stderr, "Could not open test.wav: %s\n", SDL_GetError() ) ;
}
else
{
/* Do stuff with the WAV data, and then... */
SDL_FreeWAV( wav_buffer ) ;
}
if( SDL_OpenAudio( &desired, &obtained ) == 0 )
{
printStatus( ) ;
SDL_PauseAudio( 0 ) ;
printStatus( ) ;
SDL_PauseAudio( 1 ) ;
printStatus( ) ;
SDL_CloseAudio( ) ;
printStatus( ) ;
}
SDL_AudioSpec want, have ;
SDL_AudioDeviceID dev ;
SDL_memset( &want, 0, sizeof( want ) ) ;
want.freq = 4800 ;
want.format = AUDIO_F32 ;
want.channels = 2 ;
want.samples = 4096 ;
want.callback = MyAudioCallback ;
dev = SDL_OpenAudioDevice( NULL, 0, &want, &have, SDL_AUDIO_ALLOW_FORMAT_CHANGE ) ;
if ( dev == 0 )
{
SDL_Log( "Failed to open audio: %s", SDL_GetError() ) ;
}
else
{
if( have.format != want.format )
{
SDL_Log( "We didn't get Float32 audio format." ) ;
}
SDL_PauseAudioDevice( dev, 1 ) ; /* stops audio device */
SDL_Delay( 5000 ) ;
SDL_PauseAudioDevice( dev, 0 ) ; /* Audio callback starts running again. */
}