我正在录制音频以将其发送到 Google 语音到文本,但是当我使用 naudio 制作音频时,它只记录了我 5 秒,然后从那里停止录制。我复制了C#中的代码,这是我第一次使用这个API,但我不知道为什么它会打断我,如果我按下保存按钮时它应该停止录制,应用程序是一个带有2个按钮的简单表单,一个用于录制,另一个用于停止。
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private BufferedWaveProvider bwp;
WaveIn waveIn;
WaveOut waveOut;
WaveFileWriter writer;
WaveFileReader reader;
string output = "audio.raw";
public Form1()
{
InitializeComponent();
waveOut = new WaveOut();
waveIn = new WaveIn();
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
bwp = new BufferedWaveProvider(waveIn.WaveFormat);
bwp.DiscardOnBufferOverflow = true;
btnRecordVoice.Enabled = true;
btnSave.Enabled = false;
//btnSpeechInfo.Enabled = false;
}
private void btnRecordVoice_Click(object sender, EventArgs e)
{
if (NAudio.Wave.WaveIn.DeviceCount < 1)
{
Console.WriteLine("No se encuentra un microfono!");
return;
}
waveIn.StartRecording();
btnRecordVoice.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
waveIn.StopRecording();
if (File.Exists("audio.raw"))
File.Delete("audio.raw");
writer = new WaveFileWriter(output, waveIn.WaveFormat);
btnRecordVoice.Enabled = false;
btnSave.Enabled = false;
byte[] buffer = new byte[bwp.BufferLength];
int offset = 0;
int count = bwp.BufferLength;
var read = bwp.Read(buffer, offset, count);
if (count > 0)
{
writer.Write(buffer, offset, read);
}
waveIn.Dispose();
waveIn = null;
writer.Close();
writer = null;
reader = new WaveFileReader("audio.raw"); // (new MemoryStream(bytes));
waveOut.Init(reader);
waveOut.PlaybackStopped += new EventHandler<StoppedEventArgs>(waveOut_PlaybackStopped);
waveOut.Play();
}
void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
bwp.AddSamples(e.Buffer, 0, e.BytesRecorded);
}
private void waveOut_PlaybackStopped(object sender, StoppedEventArgs e)
{
waveOut.Stop();
reader.Close();
reader = null;
}
}
}