naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.46k stars 1.09k forks source link

Extract wav audio from video files #552

Open premingiet opened 4 years ago

premingiet commented 4 years ago

Is it possible to extract audio in wav format from any video files just with naudio ? Currently i am using ffmpeg, but i just want to use it with naudio only.

markheath commented 4 years ago

MediaFoundationReader can do this with some video files, but you'll probably get more comprehensive format coverage with ffmpeg

vbasiccd commented 3 years ago

Here is an example of how I have used MediaFoundationReader in C#. However, this does require that the proper codec to read the video is already installed on the computer. If that assumption cannot be made, then ffmpeg may be your only option.

// convert the video's audio track to Wave audio data
// this only works if the proper video codec is installed
using (MemoryStream audioStream = new MemoryStream())
{
    using (MediaFoundationReader mediaReader = new MediaFoundationReader( [VIDEO FILE PATH HERE] ))
    {
        if (mediaReader.CanRead)
        {
            // move to the beginning of the mediaReader stream
            mediaReader.Seek(0, SeekOrigin.Begin);

            // convert the audio track to Wave data and save to audioStream
            WaveFileWriter.WriteWavFileToStream(audioStream, mediaReader);

            audioStream.Seek(0, SeekOrigin.Begin);
        }
    }
}