这个NAudio重新采样音频是否正确实现?

时间:2018-01-03 18:32:04

标签: c# audio naudio

我已经使用了Mark Heath's example使用MixingSampleProvider,但他说他没有做过的事情之一就是重新采样。所以我自己也做过这样的事情,但是虽然音频播放得很好,但如果有人能确认我已经正确地做到了,我将不胜感激。

我使用resampledAudio创建了MediaFoundationResampler,而不是从我audioFileReader读取的resampledAudio中读取。但是,WaveToSampleProvider没有.Length属性,所以我仍然使用audioFileReader.Length作为List<float>的大小,并假设它们的长度相同,因为它是相同的音频文件?

class CachedSound
{
    public float[] AudioData { get; private set; }
    public WaveFormat WaveFormat { get; private set; }
    public CachedSound(string audioFileName)
    {
        using (var audioFileReader = new AudioFileReader(audioFileName))
        {
            WaveToSampleProvider resampledAudio;

            resampledAudio = new WaveToSampleProvider(new MediaFoundationResampler(new SampleToWaveProvider(audioFileReader), WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)) { ResamplerQuality = 60 });
            WaveFormat = resampledAudio.WaveFormat;

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

我遇到的另一个问题是我最初决定检查音频是否需要首先重新采样:

if (audioFileReader.WaveFormat.SampleRate != 44100)
{
     resampledAudio = new WaveToSampleProvider(new MediaFoundationResampler(new SampleToWaveProvider(audioFileReader), WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)) { ResamplerQuality = 60 });
} else
{
    resampledAudio = ??; //I'm not sure how to convert from an AudioFileReader to a WaveToSampleProvider
}

但正如评论所暗示的那样,如果音频不需要重新采样,我如何将音频输入resampledAudio,以便它可以被读取,因为它们是不同类型的?我能想到的唯一另一个选择是重复读取音频的代码,这样如果它没有被重新采样则会从audioFileReader读取,如果是resampledAudio,则会从String mimeType = new MimetypesFileTypeMap().getContentType(document);读取。

1 个答案:

答案 0 :(得分:0)

@application.route('/active/', methods=['GET']) def app_start(): result = t.activate() return jsonify(result) @application.route('/last/', methods=['GET']) def app_query(): result = t.queryLast() return jsonify(result) 声明为resampledAudio,以便您可以直接为其分配ISampleProvider