Reputation: 17
i am trying to display the recording time while recording with NAudio Library Using C# windows Form Timer.This is the Code what i am trying to achieve.The problem i am having with this code is that timer's timing does not match with the length of recording.I want timer's timing and recording timing to be synchronized!
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();
}
}
Upvotes: 2
Views: 1066
Reputation: 503
You're updating seconds inside your timerSoundRecord_Tick at each tick. These are very different measurements.
Just make your length variable from the method waveSource_DataAvailable global and then check against it in timerSoundRecord_Tick, instead of using that variable seconds you're increasing.
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++;
}
Upvotes: 2