使用Naudio播放文件时检测当前音量级别

时间:2012-10-30 15:39:47

标签: c# c#-4.0 naudio

所以我有

    IWavePlayer waveOutDevice;
    WaveStream mainOutputStream;
    WaveChannel32 volumeStream;

    private WaveStream CreateInputStream(string fileName)
    {
        WaveChannel32 inputStream;
        if (fileName.EndsWith(".mp3"))
        {
            WaveStream mp3Reader = new Mp3FileReader(fileName);
            inputStream = new WaveChannel32(mp3Reader);
        }
        else
        {
            throw new InvalidOperationException("Unsupported extension");
        }
        volumeStream = inputStream;
        return volumeStream;
    }

    private void Stop()
    {
        if (waveOutDevice != null)
        {
            waveOutDevice.Stop();
        }
        if (mainOutputStream != null)
        {
            // this one really closes the file and ACM conversion
            volumeStream.Close();
            volumeStream = null;
            // this one does the metering stream
            mainOutputStream.Close();
            mainOutputStream = null;
        }
        if (waveOutDevice != null)
        {
            waveOutDevice.Dispose();
            waveOutDevice = null;
        }
    }

    private void Play(string was)
    {
        waveOutDevice = new WaveOut();
        mainOutputStream = CreateInputStream(was);
        waveOutDevice.Init(mainOutputStream);
        waveOutDevice.Play();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Play(@"E:\Eigene Audiodateien\Musik\Alben\Pur\Abenteuerland\ -  - .mp3");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Stop();
    }

有一个停止按钮(button1),停止播放。加载表单后,将播放该文件。当文件正在播放时,我希望通过运行函数来获取文件的当前音量。那么像这样的函数在“......”看起来像什么?

private int currentVolumeLevel(...some suitable parameters...)
{
  int currentVolumeLevelValue = 0;
  //....
  return currentVolumeLevelValue;
}

我不是在谈论你可以用windows的声音控制来调节音量。我正在谈论当前播放的声音文件的音量在它正在播放的位置,基于像byte []数组这样的东西。

1 个答案:

答案 0 :(得分:1)

NAudioDemo展示了如何做到这一点。在AudioPlaybackPanel.cs中查看如何将MeteringSampleProvider添加到回放管道中。 MeteringSampleProvider会定期提出StreamVolume个事件,告诉您在过去100毫秒内收到的最大样本值(这是可配置的)。您需要决定是否要在任何软件音量调整之前或之后放置MeteringSampleProvider(对于通常在之前的波形绘制,以及通常在之后的音量计量)

这是一个有效的WindowsForms演示,将流量写入控制台:

var player = new WaveOut();
var file = new AudioFileReader(@"test.mp3");
var meter = new MeteringSampleProvider(file);
meter.StreamVolume += (s,e) => Console.WriteLine("{0} - {1}", e.MaxSampleValues[0],e.MaxSampleValues[1]);
player.Init(new SampleToWaveProvider(meter));

var form = new Form();
form.Load += (s,e) => player.Play();
form.FormClosed += (s,e) => player.Dispose();
form.ShowDialog();