NAudio不播放RawSourceWaveStream

时间:2018-11-17 22:43:32

标签: c# naudio memorystream

我想在录制到文件时播放波形音频流。 我尝试使用MemoryStreamRawSourceWaveStream来达到这个结果。 似乎可以正常工作,音频已正确记录在文件中,但是当我播放流中的音频时,没有任何播放。

这是我的源代码,会很高兴告诉我问题出在哪里吗?

谢谢。

using System;
using System.Windows.Forms;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using static System.Environment;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        WaveFileWriter fileWriter;
        WaveOut outputSound;
        WaveIn waveSource;
        RawSourceWaveStream RSS;
        OffsetSampleProvider offsetSampleProvider;
        Stream sourceStream;

        string fileName = GetFolderPath(SpecialFolder.CommonApplicationData) + "\\temp.wav";

        public Form1()
        {
            InitializeComponent();

            outputSound = new WaveOut();
            waveSource = new WaveIn();
            waveSource.WaveFormat = new WaveFormat(8000, 16, 1);
            waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
            fileWriter = new WaveFileWriter(fileName, waveSource.WaveFormat);
            sourceStream = new MemoryStream();

            waveSource.StartRecording();
        }

        private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
        {
            fileWriter.Write(e.Buffer, 0, e.BytesRecorded);
            sourceStream.Write(e.Buffer, 0, e.BytesRecorded);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            RSS = new RawSourceWaveStream(sourceStream, waveSource.WaveFormat);
            offsetSampleProvider = new OffsetSampleProvider(RSS.ToSampleProvider());
            offsetSampleProvider.SkipOver = TimeSpan.FromMilliseconds(0);
            offsetSampleProvider.Take = TimeSpan.FromMilliseconds(3000);
            outputSound.Init(offsetSampleProvider);
            outputSound.Play();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我找到了问题所在。

行后:

RSS = new RawSourceWaveStream(sourceStream, waveSource.WaveFormat);

我必须将RawSourceWaveStream的位置设置为0。

RSS.Position = 0;