为什么 NAudio 在播放文件之后而不是之前读取零以缓冲?

Why does NAudio read zeros to buffer after playing the file but not before?

以下代码将成功加载、播放、编辑音频样本并(几乎)写入音频文件。我说几乎是因为当我注释掉 "Play" 代码时它可以工作,但将其留在原处会导致缓冲区读取:

audioFile.Read(buffer, 0, numSamples);

结果为零。

我需要以某种方式重置音频文件吗?我找到的所有例子都没有提到任何需要这个。

using System;
using NAudio.Wave;

namespace NAudioTest
{
class TestPlayer
{
    static void Main(string[] args)
    {
        string infileName = "c:\temp\pink.wav";
        string outfileName = "c:\temp\pink_out.wav";

        // load the file
        var audioFile = new AudioFileReader(infileName);

        // play the file
        var outputDevice = new WaveOutEvent();
        outputDevice.Init(audioFile);
        outputDevice.Play();
        //Since Play only means "start playing" and isn't blocking, we can wait in a loop until playback finishes....
        while (outputDevice.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(1000); }

        // edit the samples in file
        int fs = audioFile.WaveFormat.SampleRate;
        int numSamples = (int)audioFile.Length / sizeof(float); // length is the number of bytes - 4 bytes in a float

        float[] buffer = new float[numSamples];
        audioFile.Read(buffer, 0, numSamples);

        float volume = 0.5f;
        for (int n = 0; n < numSamples; n++) { buffer[n] *= volume; }

        // write edited samples to new file
        var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat);
        writer.WriteSamples(buffer,0,numSamples);
    }
}

}

您必须先对您的编写器调用 Dispose,然后它才能成为有效的 WAV 文件。我建议你把它放在 using 块中。

using(var writer = new WaveFileWriter(outfileName,audioFile.WaveFormat))
{
    writer.WriteSamples(buffer,0,numSamples);
}