c# NAudio 录音功能实现

1.首先新建引用类  RecordController

 

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;

        }

    }

 

简单的调用代码。

    RecordController record = new RecordController();

       

   private void button1_Click(object sender, EventArgs e)

        {

            record.StartRecord("e:\\rec.wav");

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            record.StopRecord();

        }

 

posted @ 2021-04-20 16:56  MaxBruce  阅读(686)  评论(0编辑  收藏  举报