乐趣区

关于c#:cNAudio-录音功能实现

在网上找了很多相似录音教程成果都不好,或基本不能录音,代码由网上借鉴批改(残缺实现录音播放性能)

NAudio

NAudio 为.NET 平台下的开源库,采纳 ML-PL 协定,开源地址:https://github.com/naudio/NAudio。

NAudio 功能强大,且其入门容易。
弱小在于:它反对许多音频操作,可实现多种 API 播放与录制、多种不同音频格式、音频格式转换(重采样、位深、声道等)、音频编码、多通道播放、音频成果解决等等(具体介绍能够看 Github readme)。

新建 RecordController

首先新建援用类 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();

/// <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);
}

实现代码后测试是能失常录音

退出移动版