openal-demo2.bac

'
' Demo program on how to play an OGG file. It needs the Public Domain 'stb_vorbis.c' file from:
'
' https://github.com/nothings/stb
'
' This program first will fully decode the OGG file, and then start playing using OpenAL.
'
' Created by Peter van Eerten, December 2015 - GPL v3.
'
'-----------------------------------------------------------------------------------------------------------

INCLUDE openal.bac

CONST file$ = "music.ogg"                                          : ' File to convert to PCM data

' STB Ogg Vorbis decoding -----------------------------------------------------------------------------------

PRAGMA INCLUDE stb-master/stb_vorbis.c                             : ' Include the stb_vorbis header file

DECLARE channels, sample_rate, samples TYPE int
DECLARE data TYPE short*

PRINT "Decoding, please wait..."

samples = stb_vorbis_decode_filename(file$, &channels, &sample_rate, &data)

PRINT "Channels: ", channels
PRINT "Samples: ", samples
PRINT "Sample rate: ", sample_rate

' OpenAL sound renderer -------------------------------------------------------------------------------------

DECLARE buffer, source, state TYPE int
DECLARE device, context TYPE void*

device = alcOpenDevice(NULL)                                       : ' Initialize sound device
IF device THEN
    context = alcCreateContext(device, NULL)                       : ' Create OpenAL context
    alcMakeContextCurrent(context)                                 : ' We are going to use this context
ELSE
    PRINT "Cannot open device."
    END 1
ENDIF

alGenBuffers(1, &buffer)                                           : ' Create a buffer to store sound data

alBufferData(buffer, AL_FORMAT_STEREO16, data, \
                        samples*2*sizeof(short), sample_rate)      : ' Put the decoded data into the OpenAL buffer

alGenSources(1, &source)                                           : ' Generate the sources

alSourceQueueBuffers(source, 1, &buffer)                           : ' Attach the buffer to a sound source

alSourcePlay(source)                                               : ' Now start playing the sound asynchronously

REPEAT
    SLEEP 15
    alGetSourcei(source, AL_SOURCE_STATE, &state)                  : ' Check if we're still playing
UNTIL state <> AL_PLAYING

alDeleteSources(1, &source)                                        : ' Cleanup all resources
alDeleteBuffers(1, &buffer)
alcMakeContextCurrent(NULL) 
alcDestroyContext(context)
alcCloseDevice(device)
FREE data

Generated by GNU Enscript 1.6.5.90.