NAudio音量更改

6
class Sound
{

    private NAudio.Wave.BlockAlignReductionStream stream = null;
    private NAudio.Wave.DirectSoundOut output = null;
    private string fileName;

    public Sound(string fileName)
    {

        this.fileName = fileName;

    }
    public void PlaySound()
    {

        if(fileName.EndsWith(".mp3"))
        {
        NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(fileName));
        stream = new NAudio.Wave.BlockAlignReductionStream(pcm);

        }
        else if (fileName.EndsWith(".wav"))
        {
            NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(fileName));
            stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
        }
        else throw new InvalidOperationException("Not a correct audio file type.");

        output = new NAudio.Wave.DirectSoundOut();
        output.Init(stream);
        output.Play();
        output.Volume = 0.5f;
    }
    public void Volume(float vol)
    {

    }
    public void PausePlay()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
            else if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();
        }
    }
    public void Pause()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Pause();
        }
    }
    public void Play()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Paused) output.Play();
        }
    }
    public void DisposeWave()
    {
        if (output != null)
        {
            if (output.PlaybackState == NAudio.Wave.PlaybackState.Playing) output.Stop();
            output.Dispose();
            output = null;
        }
        if (stream != null)
        {
            stream.Dispose();
            stream = null;
        }
    }
    public bool Over()
    {
        if (stream.Position == stream.Length)
            return true;
        return false;
    }
    public void Loop()
    {

        if (Over())
        {
            stream.Position = 0;
            output.Play();

        }

    }

我真的不知道这里的问题是什么,如果能帮忙就太好了,我正在尝试更改输出音频的音量。

当我编译这段代码时,在 output.volume = 0.5 处出现了一个错误。错误信息如下:

在 DirectSoundOut 上设置音量不受支持,请调整您的 WaveProvider 的音量。


2
+1 对于 new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(fileName)) 技巧,它帮助我在使用 Mp3FileReader 时访问 Volume 属性(该属性本身不包含在其中)。 - Sam
1个回答

6

这意味着,应该使用 WaveChannel32 上的 Volume 属性。此外,除非您使用的是旧版本的 NAudio,否则 BlockAlignReductionStreamWaveFormatConversion 流都是不必要的,因为 MP3FileReader 会发出 PCM。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接