NAudio WaveFileWriter 不会将文件大小写入波形文件

NAudio WaveFileWriter doesn't write file size to wave file

我正在尝试使用 NAudio 通过 WasapiLoopbackCapture 和 WaveFileWriter 在 C# 中录制一些声音。

问题是录制完成后,WAV/RIFF header 中的“大小”字段设置为 0,导致文件无法播放。

我正在使用以下代码:

    WasapiLoopbackCapture CaptureInstance = null;
    WaveFileWriter RecordedAudioWriter = null;
    void StartSoundRecord()
    {

        string outputFilePath = @"C:\RecordedSound.wav";

        // Redefine the capturer instance with a new instance of the LoopbackCapture class
        CaptureInstance = new WasapiLoopbackCapture();

        // Redefine the audio writer instance with the given configuration
        RecordedAudioWriter = new WaveFileWriter(outputFilePath, CaptureInstance.WaveFormat);
        
        // When the capturer receives audio, start writing the buffer into the mentioned file
        CaptureInstance.DataAvailable += (s, a) =>
        {
            // Write buffer into the file of the writer instance
            RecordedAudioWriter.Write(a.Buffer, 0, a.BytesRecorded);
        };

        // When the Capturer Stops, dispose instances of the capturer and writer
        CaptureInstance.RecordingStopped += (s, a) =>
        {
            RecordedAudioWriter.Dispose();
            RecordedAudioWriter = null;
            CaptureInstance.Dispose();
        };

        // Start audio recording !
        CaptureInstance.StartRecording();

    }

    void StopSoundRecord()
    {
        if(CaptureInstance != null)
        {
            CaptureInstance.StopRecording();
        }
    }

(借自:https://ourcodeworld.com/articles/read/702/how-to-record-the-audio-from-the-sound-card-system-audio-with-c-using-naudio-in-winforms

我正在测试的是:

    StartSoundRecord();
    Thread.Sleep(10000);
    StopSoundRecord();

我错过了什么,为什么 WaveFileWriter 不写入大小字段?我也试过在处理之前调用 Flush() 和 Close() 方法。但这没什么区别。

当然,我可以写一个方法来找出文件的大小并手动将其写入最终文件,但这似乎没有必要。

找到解决方案。

每次写入后调用 RecordedAudioWriter.Flush() 使其正常工作。

不知道这样做是否效率低下(因为我假设刷新会阻塞,直到数据写入磁盘),但对于我的应用程序来说这不是问题。