c# - NAudio 不播放 RawSourceWaveStream

标签 c# naudio memorystream

我想在录制到文件时播放波形音频流。 我尝试使用 MemoryStream 和 RawSourceWaveStream 来实现此结果。 它似乎有效,音频已正确记录在文件中,但是当我从流中播放音频时,没有播放任何内容。

这是我的源代码,请问有人能告诉我问题出在哪里吗?

谢谢。

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

最佳答案

我发现问题出在哪里了。

行后:

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

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

RSS.Position = 0;

关于c# - NAudio 不播放 RawSourceWaveStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356244/

相关文章:

c# - 将内存流表示为物理文件

c# - 将 ionic Zip 读取为内存流 C#

c# - Func<T> 的性能和继承

c# - 是否有 java.util.Properties 类的 C# 模拟

c# - 连接/加入两个或多个 WAV 文件时的咔嗒声

c# - 在播放nAudio时绘制.wav文件

c# - C#NAudio 3D声音

powershell - 在 Powershell 中,仅使用内存(没有可用的磁盘存储),如何创建大型文本文件的 zip 存档并将其附加到电子邮件中?

c# - 如何在数据表中添加图像?

c# - Id 的重复是否会导致有关 View 状态的随机错误?