Audio Examples

Opening the audio device

    procedure fill_audio( udata : pointer; stream : PUint8; len : integer );
var
wanted : TSDL_AudioSpec;
begin
// Set the audio format
wanted.freq := 22050;
wanted.format := AUDIO_S16;
wanted.channels := 2; // 1 = mono, 2 = stereo
wanted.samples := 1024; // Good low-latency value for callback
wanted.callback := fill_audio;
wanted.userdata := nil;

// Open the audio device, forcing the desired formats
if ( SDL_OpenAudio( @wanted, nil ) < 0 ) then
begin
MessageBox( 0, PChar( Format( 'Couldn''t open SDL Audio : %s', [SDL_GetError] ) ), 'Error', MB_OK or MB_ICONHAND );
exit;
end;
end;

Playing audio

var    
audio_chunk : PUint8;
audio_len : Uint32;
audoi_pos : PUint8;

(* The audio function callback takes the following parameters:
stream: A pointer to the audio buffer to be filled
len: The length (in bytes) of the audio buffer
*)
procedure fill_audio( udata : pointer; stream : PUint8; len : integer );
begin
// Only play if we have data left
if ( audio_len = 0 ) then
exit;

// Mix as much data as possible
if ( len > audio_len ) then
len := audio_len;
SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME );
inc( audio_pos, len );
dec( audio_len, len );
end;

// Load the audio data ...

....

audio_pos := audio_chunk;

// Let the callback function play the audio chunk
SDL_PauseAudio( 0 );

// Do some processing

....

// Wait for sound to complete
while ( audio_len > 0 ) do
begin
SDL_Delay( 100 ); // Sleep 1/10 second
end;
SDL_CloseAudio;