NAudio change volume in runtime

旧巷老猫 提交于 2019-12-25 03:59:10

问题


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é :)


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/20302117/naudio-change-volume-in-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!