Module FMOD_Ex

    ' This is our FMOD 'system' used for audio
    Dim FmodSystem As FMOD.System = Nothing

    ' This is the delegate used as a callback
    Dim PcmReadCallback As FMOD.SOUND_PCMREADCALLBACK = New FMOD.SOUND_PCMREADCALLBACK(AddressOf PcmReadCallbackFunction)

    ' This is the 'sound' we'll use as a demo (in this case, we'll manually fill the sound buffer as it plays via a delegate [callback]).
    Dim DemoSound As New FMOD.Sound

    ' Each sound needs to play in a channel. This is that channel.
    Dim PlayingChannel As New FMOD.Channel


    Sub Main()

        ' Result code of FMOD operations
        Dim Result As FMOD.RESULT

        ' Try to create an FMOD system
        Try
            Result = FMOD.Factory.System_Create(FmodSystem)
            ' Check the result code
            If Result <> FMOD.RESULT.OK Then
                Console.WriteLine("Error starting FMOD: {0}", Result)
                Return
            End If
        Catch ex As Exception
            ' Should only get here if something seriously goes wrong
            ' (eg missing DLL).
            Console.WriteLine("Could not start FMOD: {0}", ex.Message)
            Return
        End Try


        ' Initialise the system
        Result = FmodSystem.init(32, FMOD.INITFLAG.NORMAL, Nothing)
        If Result <> FMOD.RESULT.OK Then
            Console.WriteLine("Could not initialise system: {0}", Result)
            GoTo ShutDownFmod
        End If

        ' Now we need to create a 'sound' to play

        ' First we need to provide the information about what sort of sound we need
        Dim CreateSoundExInfo As FMOD.CREATESOUNDEXINFO = New FMOD.CREATESOUNDEXINFO()

        CreateSoundExInfo.cbsize = Marshal.SizeOf(CreateSoundExInfo)
        CreateSoundExInfo.fileoffset = 0
        CreateSoundExInfo.length = 1024                                 ' Size of the buffer
        CreateSoundExInfo.numchannels = 2                               ' Stereo
        CreateSoundExInfo.defaultfrequency = 44100                      ' Sample frequency (44.1KHz)
        CreateSoundExInfo.format = FMOD.SOUND_FORMAT.PCM16              ' 16-bit PCM
        CreateSoundExInfo.pcmreadcallback = PcmReadCallback             ' This is the delegate called to fill the buffer
        CreateSoundExInfo.pcmsetposcallback = Nothing                   ' We don't need a set position callback
        CreateSoundExInfo.dlsname = Nothing

        ' Next we actually create the sound:
        Result = FmodSystem.createSound( _
            "", _
            FMOD.MODE._2D Or FMOD.MODE.DEFAULT Or FMOD.MODE.OPENUSER Or FMOD.MODE.LOOP_NORMAL Or FMOD.MODE._2D Or FMOD.MODE.SOFTWARE Or FMOD.MODE.CREATESTREAM, _
            CreateSoundExInfo, _
            DemoSound)

        If Result <> FMOD.RESULT.OK Then
            Console.WriteLine("Couldn't create sound: {0}", Result)
            GoTo ShutDownFmod
        End If

        ' Let's try to play this sound on a channel:
        Result = FmodSystem.playSound(FMOD.CHANNELINDEX.REUSE, DemoSound, False, PlayingChannel)

        If Result <> FMOD.RESULT.OK Then
            Console.WriteLine("Couldn't play sound: {0}", Result)
            GoTo CloseSound
        End If

        ' Instructions
        Console.WriteLine("FMOD Ex demo")
        Console.WriteLine("------------")
        Console.WriteLine("s	Sine wave")
        Console.WriteLine("w	White noise")
        Console.WriteLine("Escape	Exit")


        ' Infinite loop
        Do

            ' Wait for a key:
            Do Until Console.KeyAvailable
                Thread.Sleep(100)
            Loop

            ' What was it?
            Select Case Console.ReadKey(True).Key
                Case ConsoleKey.Escape
                    Exit Do
                Case ConsoleKey.S
                    CurrentDemoMode = DemoMode.Sine
                Case ConsoleKey.W
                    CurrentDemoMode = DemoMode.WhiteNoise
            End Select

        Loop

CloseSound:
        DemoSound.release()
ShutDownFmod:
        FmodSystem.close()
        FmodSystem.release()

    End Sub

    Private Enum DemoMode
        Sine
        WhiteNoise
    End Enum

    Dim CurrentDemoMode As DemoMode = DemoMode.Sine

    Dim WhiteNoiseSource As Random = New Random()
    Dim SinePhaseL As Double = 0
    Dim SinePhaseR As Double = 0

    ' This function is called whenever the sound buffer needs topping up.
    Private Function PcmReadCallbackFunction(ByVal SoundRaw As IntPtr, ByVal Data As IntPtr, ByVal DataLen As UInteger) As FMOD.RESULT

        ' Create an array to hold our data in
        Dim SoundData(CInt(DataLen / 2 - 1)) As Short

        ' Fill this array with data to output to the sound buffer
        For i As Integer = 0 To SoundData.Length - 1
            Select Case CurrentDemoMode

                Case DemoMode.Sine

                    ' Note that as we are dealing in stereo, we must output twice as many samples.
                    ' One for the left channel, one for the right. The two are interlaced, so 'even'
                    ' samples are for the left channel and 'odd' samples are for the right channel.

                    If (i And 1) = 0 Then
                        SoundData(i) = CShort(30000D * Math.Sin(SinePhaseL))
                        SinePhaseL += 0.03D
                    Else
                        SoundData(i) = CShort(30000D * Math.Sin(SinePhaseR))
                        SinePhaseR += 0.06D
                    End If

                Case DemoMode.WhiteNoise
                    ' Just dump out random levels
                    SoundData(i) = CShort(WhiteNoiseSource.Next(CInt(Short.MaxValue) - CInt(Short.MinValue)) - Short.MaxValue)

            End Select
        Next

        ' Copy the data from the array to the sound buffer
        Marshal.Copy(SoundData, 0, Data, SoundData.Length)

        ' Everything's fine.
        Return FMOD.RESULT.OK
    End Function

End Module
