我正在使用C#中的NAudio录制音频,我需要删除所使用的停止按钮,并在一段时间延迟后自行停止录制。
记录事件的代码是
private void cmbRecord_Click(object sender, EventArgs e)
{
outputFilename = "file address";
waveInStream = new WaveIn(44100,2);
writer = new WaveFileWriter(outputFilename, waveInStream.WaveFormat);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
waveInStream.StartRecording();
// Just controling the objects on the screen.
cmbRecord.Enabled = false;
cmbStop.Enabled = true;
}
void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
{
writer.WriteData(e.Buffer, 0, e.BytesRecorded);
int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);
}
停止按钮为
private void cmbStop_Click(object sender, EventArgs e)
{
waveInStream.StopRecording();
waveInStream.Dispose();
waveInStream = null;
writer.Close();
writer = null;
cmbRecord.Enabled = true;
cmbStop.Enabled = false;
}
我需要在cmbRecord_Click事件中自动停止录制。 提前谢谢。
答案 0 :(得分:2)
使用Timer,设置Interval
并将cmbStop_Click
事件中的代码复制到计时器的OnTick
事件中。在mbRecord_Click
事件和&amp;中启用计时器请记得在cmbStop_Click
事件
修改强>
创建一个新计时器并设置其值
//将此行放在表单级别
中 System.Windows.Forms.Timer mytimer=new System.Windows.Forms.Timer(); //create a new Timer
//将这两个放在InitializeComponent()
之后的表单构造函数中;
mytimer.Interval=1000; //set the interval to 1 second.
mytimer.Tick += new EventHandler(mytimer_Tick);
在mbRecord_Click事件中启用计时器
private void cmbRecord_Click(object sender, EventArgs e)
{
outputFilename = "file address";
waveInStream = new WaveIn(44100,2);
writer = new WaveFileWriter(outputFilename, waveInStream.WaveFormat);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(waveInStream_DataAvailable);
waveInStream.StartRecording();
// Just controling the objects on the screen.
cmbRecord.Enabled = false;
cmbStop.Enabled = true;
//Enable the timer to fire
mytimer.Enabled = true;
}
1秒后停止录制..
void mytimer_Tick(object sender, EventArgs e)
{
waveInStream.StopRecording();
waveInStream.Dispose();
waveInStream = null;
writer.Close();
writer = null;
cmbRecord.Enabled = true;
cmbStop.Enabled = false;
//disable the timer here so it won't fire again...
mytimer.Enabled = false;
}
答案 1 :(得分:2)
您可能想要记住一件事 - 在调用DataAvailable
之后会有一个StopRecording
回调(或在期间,取决于所使用的回调模型) ,所以你可能想要延迟关闭WaveFileWriter,直到你写完所有内容。
查看使用NAudio的VoiceRecorder示例项目,并在60秒后停止录制。我在this article中解释了录制是如何自动停止的。
long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60;
int toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded);
if (toWrite > 0)
writer.WriteData(buffer, 0, bytesRecorded);
else
Stop();