Bug with NAudio, play mp3 in MemoryStream, VB

355 Views Asked by At

I have a function to read my mp3 from my Resources that work very well.

Unfortunately, if I pass my mouse 30, 40 or 50 times on my button it ends up by a crash on the waveOut.init: ( {" AlreadyAllocated calling waveOutOpen "} )

Public waveOut As WaveOut = New WaveOut

Private Sub Panel_Bouton_MouseEnter(sender As Object, e As EventArgs) Handles Panel_Bouton.MouseEnter
    Play_Sound()
End Sub

Public Sub Play_Sound()
    Dim mp3file As MemoryStream = New MemoryStream(My.Resources.Clic)
    'Clic.mp3 is in my Resources
    Dim mp3Reader As Mp3FileReader = New Mp3FileReader(mp3file)

    If waveOut.PlaybackState = PlaybackState.Playing Then
        waveOut.Stop()
        ' I tried this but no effect...
    End If

    waveOut.Init(mp3Reader)
    waveOut.Play()
End Sub
1

There are 1 best solutions below

0
Mark Heath On

I'd recommend against constantly calling Init on WaveOut. Instead, just have one (and it looks like you can have just one Mp3FileReader as well), and then in the Play_Sound function, set mp3Reader.Position = 0 and restart your WaveOut instance if it's stopped. (I'm assuming from your code snippet that you never want to be playing more than one instance of the sound at once).