NAudio
NAudio官网
环境
Unity2019.4.34f1c1
Window10
NAudio 1.10 .Net 3.5
录制音频
WaveInEvent类可录制音频
- StartRecording方法 启用录制
- StopRecording方法 停止录制
- DataAvailable 录制中回调
- RecordingStopped 录制结束回调
WaveFileWriter类可存储音频
Write方法可存储音频
检测麦克风设备数量
WaveIn.DeviceCount 返回音频捕获设备数量文章来源:https://www.toymoban.com/news/detail-654627.html
注意
台式电脑,可能需要插入耳机才可以启用麦克风文章来源地址https://www.toymoban.com/news/detail-654627.html
示例
- 检测到麦克风,显示开始录制按钮
- 点击开始录制按钮,显示停止录制按钮
- 点击停止录制按钮,回到步骤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();
}
}
到了这里,关于使用NAudio录制wav音频的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!