zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }

    转载于:https://www.cnblogs.com/wzwyc/p/7380265.html

     
  • 相关阅读:
    CSLA.Net 3.0.5 项目管理示例 业务基类 Project.cs
    为什么我要写博客
    LINQ 标准的查询操作符 过滤 where、index1、OfType
    LINQ 概述和演变
    sl中几个简单变量的获取
    Rails存储库从SVN转向Git
    showcase测试界面
    Silverlight读取xml
    向silverlight传递自定义参数
    RadRails1.0降临——增加Profiler、CallGraph Analyzer和Rails Shell等新特性
  • 原文地址:https://www.cnblogs.com/javalinux/p/14479806.html
Copyright © 2011-2022 走看看