Search code examples
vb.netaudioxnadirectxvolume

Play audio files(.wav) in VB.net w/ volume control


EDIT: Solved in self-answer below.

I've looked all over but I can't find anything useful for playing audio files with volume control. I tried XNA; SLIMDX and "Microsoft.VisualBasic.Devices.Audio" but nothing helped. The options I found which had volume control were too complex and I couldn't figure out how to use, and the method I have currently doesn't let you do anything more than play(background with or without loop, or pause execution until end of play) and stop.

Here's my current code:

Dim AD As New Microsoft.VisualBasic.Devices.Audio
   Sub Play()
        Dim af() As Byte = IO.File.ReadAllBytes("music.wav")
        AD.Play(af, AudioPlayMode.BackgroundLoop)
   End Sub

This loops "music.wav" in the background, but i cannot pause/seek it or control the volume. Is there any simple way(like the above) to play audio files from a buffer and control the audio volume? I've looked all over but nothing I've found works for my project.

System: Win7 64-bit

VS version: 2010

Language: VB.net

Oh one more thing, buffering the audio first is something I need for my solution as well(as you can see in my current code)

Does anyone have a solution to this? :)


Solution

  • I found the answer after a bit of searching around so here's the solution I found for my question:

    Download Naudio and add the references to your project.

    Then the following code is how to use it for loading audio from a buffer:

    Dim Wave1 As New NAudio.Wave.WaveOut 'Wave out device for playing the sound
    
    Dim xa() As Byte = IO.File.ReadAllBytes("C:\YourPath\YourWave.wav") 'Your Buffer
    
    Sub PlaySound()
    
            Dim data As New IO.MemoryStream(xa) 'Data stream for the buffer
    
            Wave1.Init(New NAudio.Wave.BlockAlignReductionStream(NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(New NAudio.Wave.WaveFileReader(data))))
    
            Wave1.Volume = 0.1 'Sets the Volume to 10%
    
            Wave1.Play()
    
    End Sub
    

    WaveFileReader can be changed to whichever reader you need(i.e. the MP3 one for ".mp3" files) to load your audio file, but the code works as-is for loading ".wav" files.

    oh and also, don't forget to

    WaveOut.Dispose()
    

    when you're done to avoid errors.

    I hope my research helps somebody :)