使用 NAudio 从麦克风录制声音。为啥不能正确地从列表中记录整个缓冲区?
Posted
技术标签:
【中文标题】使用 NAudio 从麦克风录制声音。为啥不能正确地从列表中记录整个缓冲区?【英文标题】:Record sound from microphone using NAudio. Why not works correctly record the whole buffer from the list?使用 NAudio 从麦克风录制声音。为什么不能正确地从列表中记录整个缓冲区? 【发布时间】:2017-03-20 11:53:55 【问题描述】:一天中的好时光。请告诉我为什么 2 号代码不能正常工作?播放录制的文件时,您只会听到咔哒声。虽然代码 1(工作正常),但不同之处仅在于缓冲区不是立即写入文件,而是添加到列表中,然后从列表中记录整个缓冲区后写入文件。
№1
using NAudio.Wave;
namespace Record
public partial class Form1 : Form
public Form1()
InitializeComponent();
WaveIn waveIn;
WaveFileWriter waveWriter;
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
if (waveWriter == null) return;
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
private void button1_Click(object sender, EventArgs e)
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
string outputFilename = @"D:/demo.wav";
waveIn.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(waveIn.DeviceNumber).Channels);
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveWriter = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
waveIn.StartRecording();
private void button2_Click(object sender, EventArgs e)
if (waveIn != null)
waveIn.StopRecording();
waveIn.Dispose();
waveIn = null;
if (waveWriter != null)
waveWriter.Dispose();
waveWriter = null;
№2
using NAudio.Wave;
namespace RecordReally
public partial class Form1 : Form
public Form1()
InitializeComponent();
WaveIn waveIn;
WaveFileWriter waveWriter;
string outputFilename = @"D:/demo.wav";
List<byte[]> bytes = new List<byte[]>();
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
bytes.Add(e.Buffer);
private void button1_Click(object sender, EventArgs e)
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
waveIn.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(waveIn.DeviceNumber).Channels);
waveWriter = new WaveFileWriter(outputFilename, waveIn.WaveFormat);
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveIn.StartRecording();
private void button2_Click(object sender, EventArgs e)
if (waveIn != null)
waveIn.StopRecording();
waveIn.Dispose();
waveIn = null;
foreach (byte[] buffer in bytes)
waveWriter.Write(buffer, 0, buffer.Length);
waveWriter.Flush();
if (waveWriter != null)
waveWriter.Dispose();
waveWriter = null;
【问题讨论】:
bytes.Add(e.Buffer);
不复制字节。您需要创建一个新数组并将数据复制到新数组中,然后将新数组添加到列表中。
谢谢!作品)
【参考方案1】:
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
byte[] ebuffer = new byte[e.BytesRecorded];
for (int n = 0; n < ebuffer.Length; n++)
ebuffer[n] = e.Buffer[n];
bytes.Add(ebuffer);
【讨论】:
请添加详细信息以解释其工作原理或作用,以便于理解。以上是关于使用 NAudio 从麦克风录制声音。为啥不能正确地从列表中记录整个缓冲区?的主要内容,如果未能解决你的问题,请参考以下文章