使用NAudio录制wav音频

NAudio

NAudio官网

环境

Unity2019.4.34f1c1
Window10
NAudio 1.10 .Net 3.5

录制音频

WaveInEvent类可录制音频

  1. StartRecording方法 启用录制
  2. StopRecording方法 停止录制
  3. DataAvailable 录制中回调
  4. RecordingStopped 录制结束回调

WaveFileWriter类可存储音频

Write方法可存储音频

检测麦克风设备数量

WaveIn.DeviceCount 返回音频捕获设备数量

注意

台式电脑,可能需要插入耳机才可以启用麦克风

示例

  1. 检测到麦克风,显示开始录制按钮
  2. 点击开始录制按钮,显示停止录制按钮
  3. 点击停止录制按钮,回到步骤1
using NAudio.Wave;
using System;
using System.IO;
using UnityEngine;

public class RecordNAudio : MonoBehaviour
{
    bool recording;

    string outputFolder;
    string outputFilePath
    {
        get
        {
            return Path.Combine(outputFolder, DateTime.Now.ToString("yyyyMMddHHmmss") + ".wav");
        }
    }

    WaveInEvent waveIn;
    WaveFileWriter writer;

    private void Awake()
    {
        recording = false;

        outputFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "NAudio");

        if (!Directory.Exists(outputFolder))
            Directory.CreateDirectory(outputFolder);

        waveIn = new WaveInEvent();
        waveIn.DataAvailable += Recording;
        waveIn.RecordingStopped += RecordingStopped;

        writer = null;
    }

    private void OnGUI()
    {
        if (recording == false)
        {
            if (WaveIn.DeviceCount > 0)
            {
                if (GUILayout.Button("开始录制"))
                {
                    writer = new WaveFileWriter(outputFilePath, waveIn.WaveFormat);
                    waveIn.StartRecording();
                    recording = true;
                }
            }
            else
                GUILayout.Label("无法启用麦克风,请在主机上插入耳机,尝试启用麦克风");            
        }
        else
        {
            if (GUILayout.Button("停止录制"))
            {
                waveIn.StopRecording();
                recording = false;
            }
        }
    }

    private void Recording(object sender, WaveInEventArgs e)
    {
        if (writer != null)
            writer.Write(e.Buffer, 0, e.BytesRecorded);
    }

    private void RecordingStopped(object sender, StoppedEventArgs e)
    {
        if (writer != null)
            writer.Dispose();
        writer = null;
        waveIn.Dispose();
    }
}

你可能感兴趣的:(Unity经验,音视频,c#,开发语言,NAudio)