• 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;
    }
    }

    2.在主界面引用  RecordController record = new RecordController();

    /// <summary>
    /// 耳机sidetone测试
    /// </summary>
    /// <param name="i"></param>
    public void Sidetone(int i)
    {
    string[] row = getlistviewitem(i);
    record.StartRecord("e:\rec.wav");
    if (MessageBox.Show("正在录音,点击是播放录音", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
    {
    record.StopRecord();
    ErrorFlag = false;
    row[6] = "FAIL";
    }
    else
    {
    record.StopRecord();
    string path = "e:\rec.wav";//.wav音频文件路径
    System.Media.SoundPlayer player = new System.Media.SoundPlayer(path);
    player.Play();

    if (MessageBox.Show("是否有录音", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
    {
    ErrorFlag = false;
    row[6] = "FAIL";
    }
    else
    {
    ErrorFlag = true;
    row[5] = "OK";
    row[6] = "PASS";
    }
    }
    listupdate(row, i);
    }

    完成代码后测试是能正常录音

  • 相关阅读:
    实验5&期中考试后两题
    实验四——再探类
    实验3—初识类
    10.29算法训练——poj1475双重BFS
    10.25算法训练——裸线段树
    探索邻接表
    Hadoop学习之Combiner
    关于VLM模式下linux压缩根目录空间的心得
    C#微信公众号开发系列教程四(接收普通消息)
    c#分部类型详解
  • 原文地址:https://www.cnblogs.com/ouyangkai/p/11280352.html
Copyright © 2020-2023  润新知