码迷,mamicode.com
首页 > Windows程序 > 详细

WPF使用NAudio录音

时间:2017-08-17 12:49:14      阅读:579      评论:0      收藏:0      [点我收藏+]

标签:click   ace   one   stop   stopped   star   partial   int   for   

代码:

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录音

标签:click   ace   one   stop   stopped   star   partial   int   for   

原文地址:http://www.cnblogs.com/wzwyc/p/7380265.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!