简体   繁体   中英

NAudio WaveFileWriter doesn't write file size to wave file

I'm trying to use NAudio to record some sound in C# using WasapiLoopbackCapture and WaveFileWriter.

The problem is that after the recording is finished, the "size" field in the WAV/RIFF header is set to 0, rendering the file unplayable.

I'm using the following code:

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

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

Which I'm testing with simply:

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

What am I missing, why isn't WaveFileWriter writing the size field? I have tried also calling the Flush() and Close() methods before disposing. But it makes no difference.

Sure, I could write a method to find out the size of the file and manually writing it to the final file, but that seems unnecessary.

Found the solution.

Calling RecordedAudioWriter.Flush() after every Write made it work just fine.

Don't know if doing so might be inefficient (as I assume flush is blocking until data is written to disk), but for my application that is not an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM