Search code examples
c#asp.net-corenaudio

NAudio looking for a way to read from a Stream when changing pitch instead of a File


I am using the Naudio lib in my project and I've used it already to combine MP3 files and use them. I combined them using Mp3FileReader(Stream), so it is possible to read from a stream with this object but when I try to change the audio pitch and follow their tutorial this is how it goes:

    using (var reader = new MediaFoundationReader(inPath)) //only reads from file
{
    var pitch = new SmbPitchShiftingSampleProvider(reader.ToSampleProvider());
    using(var device = new WaveOutEvent())
    {
        pitch.PitchFactor = (float)upOneTone; // or downOneTone
        // just playing the first 10 seconds of the file
        device.Init(pitch.Take(TimeSpan.FromSeconds(10)));
        device.Play();
        while(device.PlaybackState == PlaybackState.Playing)
        {
            Thread.Sleep(500);
        }
    }
}

now my problem is that MediaFoundationReader only reads from file, is there another way to load from a stream and change the pitch/ frequency.

any help will be appreciated.


Solution

  • I hope this code will help you: This function receive a Stream instead a file path.

    using System;
    using System.IO;
    using System.Threading;
    using NAudio.Wave;
    using NAudio.Wave.SampleProviders;
    namespace Test
    {
        public class HelpOnStackOverFlow
        {
            public static void PlayShift(Stream stream)
            {
                var fr = new Mp3FileReader(stream);
    
                fr.ToSampleProvider();
                var pitch = new SmbPitchShiftingSampleProvider(fr.ToSampleProvider());
    
                var rates = new float[] { 1.0594630943593f, 1.12246204830937f, 1.18920711500272f, 1.25992104989487f };
    
                foreach (var rate in rates)
                {
    
                    var device = new WaveOutEvent();
                    pitch.PitchFactor = rate;
                    device.Init(pitch.Take(TimeSpan.FromSeconds(1)));
                    device.Play();
                    Thread.Sleep(1000);
                }
            }
        }
    }