C# NAudio 录音

RT,录音并保存成wav格式的文件,本来是想用DirectX,但是找了好多资料都无法正常录音,只能用别的方法了,然后就找到了NAudio

下载地址 http://naudio.codeplex.com/

下面上在网上找的例子里面的关键类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuYinC.Recorder
{
    public interface ISpeechRecorder
    {
        void SetFileName(string fileName);
        void StartRec();
        void StopRec();
    }
}

 

using NAudio.Wave;
using System;

namespace LuYinC.Recorder
{
    class NAudioRecorder : ISpeechRecorder
    {
        public WaveIn waveSource = null;
        public WaveFileWriter waveFile = null;
        private string fileName = string.Empty;

        /// 
        /// 开始录音
        /// 
        public void StartRec()
        {
            waveSource = new WaveIn();
            waveSource.WaveFormat = new WaveFormat(16000, 16, 1); // 16bit,16KHz,Mono的录音格式

            waveSource.DataAvailable += new EventHandler(waveSource_DataAvailable);
            waveSource.RecordingStopped += new EventHandler(waveSource_RecordingStopped);

            waveFile = new WaveFileWriter(fileName, waveSource.WaveFormat);

            waveSource.StartRecording();
        }

        /// 
        /// 停止录音
        /// 
        public void StopRec()
        {
            waveSource.StopRecording();

            // Close Wave(Not needed under synchronous situation)
            if (waveSource != null)
            {
                waveSource.Dispose();
                waveSource = null;
            }

            if (waveFile != null)
            {
                waveFile.Dispose();
                waveFile = null;
            }
        }

        /// 
        /// 录音结束后保存的文件路径
        /// 
        /// 保存wav文件的路径名
        public void SetFileName(string fileName)
        {
            this.fileName = fileName;
        }

        /// 
        /// 开始录音回调函数
        /// 
        /// 
        /// 
        private void waveSource_DataAvailable(object sender, WaveInEventArgs e)
        {
            if (waveFile != null)
            {
                waveFile.Write(e.Buffer, 0, e.BytesRecorded);
                waveFile.Flush();
            }
        }

        /// 
        /// 录音结束回调函数
        /// 
        /// 
        /// 
        private void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
        {
            if (waveSource != null)
            {
                waveSource.Dispose();
                waveSource = null;
            }

            if (waveFile != null)
            {
                waveFile.Dispose();
                waveFile = null;
            }
        }
    }
}


调用方法:

recorder = new NAudioRecorder();

//开始录音
recorder.SetFileName("record.wav");
recorder.StartRec();

//结束录音
recorder.StopRec();

 

以下是我下载好的NAudio.dll文件,不知道怎么直接放上来文件包,只能发一个百度网盘的连接了

 链接:https://pan.baidu.com/s/1hundpEs 密码:i1m2

转载于:https://www.cnblogs.com/lingLuoChengMi/p/8335681.html

你可能感兴趣的:(C# NAudio 录音)