gpt4 book ai didi

c# - 使用NAudio录音时如何显示录音时间?

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:07 24 4
gpt4 key购买 nike

我正在尝试使用 C# windows Form Timer 在使用 NAudio 库录制时显示录制时间。这是我想要实现的代码。我在使用此代码时遇到的问题是计时器的时间与录音时长。我希望定时器计时和录音计时同步!

  private void buttonStart_Click(object sender, EventArgs e)
{

buttonStart.Enabled = false;
buttonStop.Enabled = true;

waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 2);

waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);

waveFile = new WaveFileWriter(@"C:\one\Test0010.wav", waveSource.WaveFormat);
waveSource.StartRecording();

}
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{

if (waveFile != null)
{

timerSoundRecord.Start();
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
var lenght = (int)(waveFile.Length / waveFile.WaveFormat.AverageBytesPerSecond);

if (lenght == 6)
{
timerSoundRecord.Stop();
waveSource.StopRecording();
buttonStop.Enabled = false;
buttonStart.Enabled = true;
}



}
}

private void timerSoundRecord_Tick(object sender, EventArgs e)
{

if (progressBarRecordSound.Value != 6)
{


seconds = seconds + 1;

labelTime.Text = @"00:0" + seconds;
progressBarRecordSound.Value++;
}
else
{
timerSoundRecord.Stop();
}
}

最佳答案

您在每次滴答时更新 timerSoundRecord_Tick 中的秒数。这些是非常不同的测量值。

只需将方法 waveSource_DataAvailable 中的长度变量设置为全局变量,然后在 timerSoundRecord_Tick 中检查它,而不是使用你正在增加的变量秒数。

  private void buttonStart_Click(object sender, EventArgs e)
{

buttonStart.Enabled = false;
buttonStop.Enabled = true;

waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 2);

waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);

waveFile = new WaveFileWriter(@"C:\one\Test0010.wav", waveSource.WaveFormat);
waveSource.StartRecording();
timerSoundRecord.Start();
}

int length = 0;
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
var lenght = (int)(waveFile.Length / waveFile.WaveFormat.AverageBytesPerSecond);

if (lenght == 6)
{
timerSoundRecord.Stop();
waveSource.StopRecording();
labelTime.Text = @"00:0" + length;
progressBarRecordSound.Value++;
buttonStop.Enabled = false;
buttonStart.Enabled = true;
}
}
}

private void timerSoundRecord_Tick(object sender, EventArgs e)
{
labelTime.Text = @"00:0" + length;
progressBarRecordSound.Value++;
}

关于c# - 使用NAudio录音时如何显示录音时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340804/

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