WPF使用NAudio录音

Posted 程序员日志

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF使用NAudio录音相关的知识,希望对你有一定的参考价值。

代码:

using NAudio.Wave;
using System.Windows;

namespace NAudioDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        RecordController record = new RecordController();
        bool startRecord = false;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!startRecord)
            {
                record.StartRecord("D:\\rec.wav");
                startRecord = true;
            }
            else
            {
                record.StopRecord();
                startRecord = false;
            }
        }
    }

    /// <summary>
    /// 录音功能控制类
    /// </summary>
    public class RecordController
    {
        public WaveIn mWavIn;
        public WaveFileWriter mWavWriter;

        /// <summary>
        /// 开始录音
        /// </summary>
        /// <param name="filePath"></param>
        public void StartRecord(string filePath)
        {
            mWavIn = new WaveIn();
            mWavIn.DataAvailable += MWavIn_DataAvailable;
            mWavIn.RecordingStopped += MWavIn_RecordingStopped;
            mWavWriter = new WaveFileWriter(filePath, mWavIn.WaveFormat);
            mWavIn.StartRecording();
        }

        /// <summary>
        /// 停止录音
        /// </summary>
        public void StopRecord()
        {
            mWavIn?.StopRecording();
            mWavIn?.Dispose();
            mWavIn = null;
            mWavWriter?.Close();
            mWavWriter = null;
        }

        private void MWavIn_RecordingStopped(object sender, StoppedEventArgs e)
        {
            mWavIn?.Dispose();
            mWavIn = null;
            mWavWriter?.Close();
            mWavWriter = null;
        }

        private void MWavIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            mWavWriter.Write(e.Buffer, 0, e.BytesRecorded);
            int secondsRecorded = (int)mWavWriter.Length / mWavWriter.WaveFormat.AverageBytesPerSecond;
        }
    }
}

 

以上是关于WPF使用NAudio录音的主要内容,如果未能解决你的问题,请参考以下文章

如何同时使用 NAudio 生成信号和录音?

NAudio Wasapi 录音和转换

NAudio录音输出流

将nAudio录音存储在变量而不是c#中的文件中

NAudio 录音中不需要的静音部分

c# Naudio 音频电平捕获和显示,仅在打开录音属性时有效