using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
namespace record24位
{
class Program
{
static void Main(string[] args)
{
// 录音对象
WaveInEvent waveIn = new WaveInEvent();
int sampleRate = 48000; //采样率
int channels = 2; //录音通道数
int bitsPerSample = 16; //位深
WaveFormat waveFormat = new WaveFormat(sampleRate, bitsPerSample, channels);
string RecordDeviceName = "麦克风阵列";
//枚举可用录音设备
for (int i = 0; i < WaveIn.DeviceCount; i++)
{
var capabilities = WaveIn.GetCapabilities(i);
Console.WriteLine("DeviceIndex:{0},ProduceName:{1}", i, capabilities.ProductName);
if (capabilities.ProductName.StartsWith(RecordDeviceName))
{
Console.WriteLine("找到指定设备:{0}", RecordDeviceName);
waveIn.DeviceNumber = i; //设置该设备为录音设备
}
}
waveIn.WaveFormat = waveFormat; //设置录音格式
// 创建WaveFileWriter对象来保存录音数据 路径在bin文件下
WaveFileWriter writer = new WaveFileWriter("recorded.wav", waveFormat);
//编写器
StreamWriter mStreamWriter = new StreamWriter("Record.txt", false, new System.Text.UTF8Encoding(false));
// 设置录音回调函数
int bitIndex = bitsPerSample / 8;
waveIn.DataAvailable += (sender, e) =>
{
// 将录音数据写入文件
writer.Write(e.Buffer, 0, e.BytesRecorded);
for (int i = 0; i < e.BytesRecorded/ bitIndex; i++)
{
//24bit,导出的数据
//int sample = (int)((e.Buffer[i * bitIndex + 2] << 16) | (e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);
//16bit 将两个byte数据组合成一个short数据
short sample = (short)((e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]);
mStreamWriter.Write("{0},", sample);
}
};
try
{
//尝试打开录音设备,如果设备支持设置的WaveFormat,则能够成功打开
waveIn.StartRecording();
Console.WriteLine("开始录音");
}
catch (Exception ex)
{
Console.WriteLine($"错误信息:{ex.Message}");
}
Console.WriteLine("请按任意键结束录音");
Console.ReadKey();
waveIn.StopRecording(); //停止录音
writer.Close();
mStreamWriter.Close();
waveIn.Dispose();
}
}
}
|