为什么NA​​udio在播放文件后会读取零缓冲区而不是之前?

时间:2018-03-21 15:13:46

标签: c# vlc naudio audacity

以下代码将成功,加载,播放,编辑音频样本和(几乎)写入音频文件。我说几乎是因为当我评论" Play"代码可以工作,但保留它会导致缓冲区读取:

audioFile.Read(buffer, 0, numSamples);

导致零。

我是否需要以某种方式重置audioFile?我发现的所有例子都没有提到任何需要。

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);
    }
}

}

1 个答案:

答案 0 :(得分:1)

在作家是有效的WAV文件之前,您必须在作家上调用Dispose。我建议您将其放在using块中。

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