'
' Small demonstration on how to p[ay an MP3 file with BaCon and SDL/SDL_Mixer.
'
' March 2012, PvE.
'---------------------------------------------------------------------------------------

TRAP LOCAL

' Get the separate arguments
OPTION COLLAPSE TRUE
SPLIT ARGUMENT$ BY " " TO arg$ SIZE amount

IF amount < 2 THEN
    PRINT "Usage: mp3 <file>"
    END
ENDIF

' Check if the file exists
IF NOT(FILEEXISTS(arg$[1])) THEN
        PRINT "File ", arg$[1], " not found!"
        END
END IF

' Get the functions from SDL and SDL_Mixer
IMPORT "SDL_Init(long)" FROM "libSDL-1.2.so.0" TYPE int
IMPORT "SDL_Quit(void)" FROM "libSDL-1.2.so.0" TYPE void
IMPORT "Mix_OpenAudio(int,long,int,int)" FROM "libSDL_mixer-1.2.so.0" TYPE int
IMPORT "Mix_CloseAudio(void)" FROM "libSDL_mixer-1.2.so.0" TYPE void
IMPORT "Mix_LoadMUS(char*)" FROM "libSDL_mixer-1.2.so.0" TYPE long
IMPORT "Mix_PlayMusic(long,int)" FROM "libSDL_mixer-1.2.so.0" TYPE int
IMPORT "Mix_HookMusicFinished(void*)" FROM "libSDL_mixer-1.2.so.0" TYPE void
IMPORT "Mix_HaltMusic(void)" FROM "libSDL_mixer-1.2.so.0" TYPE int
IMPORT "Mix_FreeMusic(long)" FROM "libSDL_mixer-1.2.so.0" TYPE void

' From the SDL header files
CONST AUDIO_S16 = 0x8010
CONST SDL_INIT_AUDIO = 0x00000010

'---------------------------------------------------------------------------------------

' Callback to execute when the music is finished
SUB musicDone

        Mix_HaltMusic()
        Mix_FreeMusic(music)

END SUB

'---------------------------------------------------------------------------------------

DECLARE done, audio_format, music
DECLARE audio_rate, audio_channels, audio_buffers TYPE int

' Initialize SDL
SDL_Init(SDL_INIT_AUDIO)

' Set the audio device with our parameters
audio_rate = 44100
audio_channels = 2
audio_buffers = 4096
audio_format = AUDIO_S16

IF Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) > 0 THEN
        PRINT "Unable to open audio! Exiting..."
        END
END IF

' Load the music file
music = Mix_LoadMUS(arg$[1])

' Start playing the music
Mix_PlayMusic(music, 0)

' Define callback to execute when the music has stopped naturally
Mix_HookMusicFinished(musicDone)

' Press key to interrupt
PRINT "Press key to stop..."
key = GETKEY

' Cleanup
PRINT "Cleaning up..."
Mix_CloseAudio()
SDL_Quit()
PRINT "Done."