C# - NAudio - 如何在阅读时更改浮点数[]上的采样率?

时间:2015-08-26 22:14:33

标签: naudio sample rate pitch

我正在编写我的第一个音频应用程序,而且我在尝试更改缓存声音的采样率时挣扎了好几个小时。 我正在使用NAudio,我可以更改音量,调整我的ISampleProvider的Read()方法。

这是CachedSound类:

public class CachedSound
{
    public float[] AudioData { get; private set; }
    public WaveFormat WaveFormat { get; set; }

    public CachedSound(string audioFileName)
    {
        using (var audioFileReader = new AudioFileReader(audioFileName))
        {
            WaveFormat = audioFileReader.WaveFormat;

            var wholeFile = new List<float>((int)(audioFileReader.Length / 4));
            var readBuffer = new float[audioFileReader.WaveFormat.SampleRate * audioFileReader.WaveFormat.Channels];
            int samplesRead;
            while ((samplesRead = audioFileReader.Read(readBuffer, 0, readBuffer.Length)) > 0)
            {
                wholeFile.AddRange(readBuffer.Take(samplesRead));
            }
            AudioData = wholeFile.ToArray();
        }
    }
}

这是CachedSoundSampleProvider类:

using NAudio.Wave;
using System;

public delegate void PlaybackEndedHandler();

public class CachedSoundSampleProvider : ISampleProvider
{
    public event PlaybackEndedHandler PlaybackEnded;
    private CachedSound cachedSound;

    private long _position;
    public long Position {
        get { return _position; }
        set { _position = value; }
    }

    private float _volume;
    public float Volume {
        get { return _volume; }
        set { _volume = value; }
    }

    private float _pitchMultiplicator;
    public float PitchMultiplicator
    {
        get { return _pitchMultiplicator; }
        set { _pitchMultiplicator = value; }
    }

    public WaveFormat OriginalWaveFormat { get; set; }

    public WaveFormat WaveFormat {
        get { return cachedSound.WaveFormat; }
    }

    //Constructeur
    public CachedSoundSampleProvider(CachedSound _cachedSound)
    {
        cachedSound = _cachedSound;
        OriginalWaveFormat = WaveFormat;
    }

    public int Read(float[] destBuffer, int offset, int numBytes)
    {
        long availableSamples = cachedSound.AudioData.Length - Position;
        long samplesToCopy = Math.Min(availableSamples, numBytes);

        //Changing original audio data samplerate
        //Double speed to check if working
        cachedSound.WaveFormat = new WaveFormat(cachedSound.WaveFormat.SampleRate*2, cachedSound.WaveFormat.Channels);
        Array.Copy(cachedSound.AudioData, Position, destBuffer, offset, samplesToCopy);

        //Changing Volume
        for (int i = 0; i < destBuffer.Length; ++i)
            destBuffer[i] *= (Volume > -40) ? (float)Math.Pow(10.0f, Volume * 0.05f) : 0;

        Position += samplesToCopy;
        if (availableSamples == 0) PlaybackEnded();
        return (int)samplesToCopy;
    }
}

我不知道如何实现这一目标。 我的目标很简单,我希望能够实时调整采样率。 我认为在ISampleProvider界面上无法更改它。

这就是我尝试在原始audioData上更改它的原因。

提前感谢您的帮助! :)

0 个答案:

没有答案