user3052442
user3052442

Reputation: 15

NAudio change volume in runtime

I would like change the volume of my audiostream in runtime. I use this code: Public Volume as Single = 0.01 Dim Wave1 As New NAudio.Wave.WaveOut

Dim xa() As Byte = IO.File.ReadAllBytes("C:\Song - Come Out and Play.wav")

Sub PlaySound()

    Dim data As New IO.MemoryStream(xa)

    Wave1.Init(New NAudio.Wave.BlockAlignReductionStream(NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(New NAudio.Wave.WaveFileReader(data))))

    Wave1.Volume = Volume

    Wave1.Play()

End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    PlaySound()
End Sub

But how can i change the Volume in runtime? It doesn´t change, when i click a button with

Volume = 2.0

Why?

Thanks for this.

Second problem: How must i change this code, to play MP3 instead of WAV? Because WAV is to large..

Thanks for both :)

Sorry for my bad English.

Regards, René :)

Upvotes: 1

Views: 7344

Answers (2)

Corey
Corey

Reputation: 16564

First question about volume was answered by Mark - Volume is in the range 0.0 <= volume <= 1.0, so setting the volume to 2.0 is invalid.

As to how to use MP3 files...

You can replace the WaveFileReader with Mp3FileReader in your code if the data you are feeding in is MP3 instead of WAV. If the data is always coming from a file you could use new AudioFileReader(filename) instead and let it work out what the compression format is.

Here's your code with MP3 instead of WAV:

Public Volume as Single = 0.01

Dim Wave1 As New NAudio.Wave.WaveOut

Dim xa() As Byte = IO.File.ReadAllBytes("C:\Song - Come Out and Play.mp3")

Sub PlaySound()

    Dim data As New IO.MemoryStream(xa)

    Wave1.Init( _
        New NAudio.Wave.BlockAlignReductionStream( _
            NAudio.Wave.WaveFormatConversionStream.CreatePcmStream( _
                New NAudio.Wave.Mp3FileReader(data) _
        )))

    Wave1.Volume = Volume

    Wave1.Play()

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    PlaySound()
End Sub

Upvotes: 1

Mark Heath
Mark Heath

Reputation: 49482

The volume property has a maximum value of 1.0 which indicates 1.0. The latest NAudio will throw an exception if you try to set it any higher.

Upvotes: 0

Related Questions