• 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();

            }

  • 相关阅读:
    第十四周课程总结&实验报告(简单记事本的实现)
    第十三周课程总结
    第十二周课程总结
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第五周课程总结&实验报告(四)
    2019JAVA课程总结
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14681814.html
Copyright © 2020-2023  润新知