gpt4 book ai didi

c# - 使用NAudio录制来自麦克风的声音。为什么不能正确记录列表中的整个缓冲区?

转载 作者:行者123 更新时间:2023-12-03 00:34:49 31 4
gpt4 key购买 nike

一天中的好时光。请告诉我为什么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;
}
}
}
}

最佳答案

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

关于c# - 使用NAudio录制来自麦克风的声音。为什么不能正确记录列表中的整个缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902916/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com