Search code examples
naudioms-media-foundationresampling

MFT NAudio Resampling on the fly


I want to resample an audio file using NAudio and MFT on-the-fly.

For example, I have the following audio file:

File name: MyAudioFile.mp3

Duration: 10 sec

When this file is being played, I only want to resample that particular position to WAV in the desired format.

So, if the length of "MyAudioFile.mp3" is 10 sec, and the "current play position" is 2.5 sec, I want to resample only that portion of data into WAV format at the sampling rate of 48 KHz.

When the audio progresses further, again, only the "current play position" must be resampled.

I tried the following code:

    WaveStream reader = new MediaFoundationReaderRT([path of 
    "MyAudioFile.mp3"]);

    MemoryStream outMemStream = new MemoryStream(); //Decode to memory 
    stream

    using (reader)
    using (var resampler = new MediaFoundationResampler(reader, 
    resampler.WaveFormat))
    {
        WaveFileWriter.CreateWaveFile(outMemStream, resampler);
        rsws = new RawSourceWaveStream(outMemStream, resampler.WaveFormat);
    }

    WaveChannel32 waveformInputStream = new WaveChannel32(rsws);

The resampling happens properly; however it resamples the whole audio file, which takes time.

What I am looking at is just resampling the "current play position" of the audio, and discard any other position information.

Thanks! Appreciate if you can provide some sample.


Solution

  • To resample on the fly, just pass the reader directly into MediaFoundationResampler. You will now have an ISampleProvider so you won't be able to use WaveChannel32, but really that is an obsolete class now, and you should be able to do anything you need with other ISampleProvider classes from NAudio.