[SDL] SDL_MixAudio() crash when trying to play converted audio data

Ryan C. Gordon icculus at clutteredmind.org
Tue Jul 9 19:30:01 PDT 2002

>         /* Decode the sound file */
>         Sound_SetBufferSize (sample, len);

Don't do this everytime; you don't want to be calling realloc() every 100
milliseconds or so while the audio device is open. Look at playsound.c in
the SDL_sound package for a very robust example of decoding during
callback ("robust" means "complex" in this case, but you could still trim
a lot of that out and still have a very stable means of playback).

>         /* Convert the audio data (sample rate, channels, etc.) and mix
>            it */
>         info = &sample->actual;
>         SDL_BuildAudioCVT (&cvt,
>                 info->format, info->channels, info->rate,
>                 AUDIO_S16,    2,              44100);
>         cvt.buf = (Uint8 *) malloc (amount * cvt.len_mult);
>         memcpy (cvt.buf, sample->buffer, amount);
>         cvt.len = amount;
>         SDL_ConvertAudio (&cvt);

Just tell SDL_sound to do the conversion during the call to
Sound_NewSample(), and then Sound_Decode() will convert the data before
handing it back to you.

>         /* This function makes the program crash when playing the
>            22khz wav file, but works just fine when playing a 44khz MP3;
>            when commented out, the program doesn't crash */
>         SDL_MixAudio (stream, cvt.buf, amount * cvt.len_mult,
>                       SDL_MIX_MAXVOLUME);

After conversion, you might be mixing more data than the audio callback
wants, since the size of the data might double or more...best to let
SDL_sound handle this internally, or you'll end up with skips in the audio
at best...but probably segfaults when you write too much to (stream).

>                 sample = Sound_NewSampleFromFile (argv[1], NULL,
>                                                   1024 * 4);

Just replace that (NULL) with a Sound_AudioInfo structure.

>                 sample = Sound_NewSampleFromFile ("gunshot.wav", NULL,
>                                                   1024 * 4);

(And that one too, to be safe)


More information about the SDL mailing list