如何显示录制时间,而录制与NAudio
本文关键字:NAudio 时间 何显示 显示 | 更新日期: 2023-09-27 18:01:58
我试图在使用c# windows窗体定时器录制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();
}
}
你在每次滴答时更新timesoundrecord_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++;
}