NAudio 在改变音高而不是文件时寻找从流中读取的方法

问题描述

我在我的项目中使用 Naudio 库,我已经用它来组合 MP3 文件并使用它们。 我使用 Mp3FileReader(Stream) 将它们组合在一起,因此可以使用此对象从流中读取,但是当我尝试更改音频音调并按照他们的教程进行操作时,情况如下:

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

现在我的问题是 MediaFoundationReader 只从文件中读取,是否有另一种方法可以从流加载并更改音高/频率。

任何帮助将不胜感激。

解决方法

希望这段代码能帮到你: 此函数接收 Stream 而不是文件路径。

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