繁体   English   中英

如何自动开始和停止录音?

[英]How to start and stop audio recording automatically?

我正在 C# 中使用 NAudio 录制音频,我需要自动开始录制并在 6 秒后自动停止。 它在 6 秒后开始和停止,但音频重复,似乎进入无限循环。

这是代码:

public partial class Form1 : Form
{
    System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer(); //create a new Timer

    private WaveFileWriter RecordedAudioWriter = null;
    private WasapiLoopbackCapture CaptureInstance = null;

    public Form1()
    {
        InitializeComponent();
        mytimer.Interval = 6000; //set the interval to 1 second.
        mytimer.Tick += new EventHandler(mytimer_Tick);
        mytimer.Enabled = true;
    }

    private void mytimer_Tick(object sender, EventArgs e)
    {
        mytimer.Start();
        string outputFilePath = @"D:\deep\New\Transfare\tf-File\output\out.wav";

        // Redefine the capturer instance with a new instance of the LoopbackCapture class
        this.CaptureInstance = new WasapiLoopbackCapture();

        // Redefine the audio writer instance with the given configuration
        this.RecordedAudioWriter = new WaveFileWriter(outputFilePath, CaptureInstance.WaveFormat);

        // When the capturer receives audio, start writing the buffer into the mentioned file
        this.CaptureInstance.DataAvailable += (s, a) =>
        {
            this.RecordedAudioWriter.Write(a.Buffer, 0, a.BytesRecorded);
        };

        // When the Capturer Stops
        this.CaptureInstance.RecordingStopped += (s, a) =>
        {
            this.RecordedAudioWriter.Dispose();
            this.RecordedAudioWriter = null;
            CaptureInstance.Dispose();
        };
        // Start recording !
        this.CaptureInstance.StartRecording();
        stoprec(sender,e);
    }

  private void stoprec(object sender, EventArgs e)
  {
      this.CaptureInstance.StopRecording();
      this.mytimer.Enabled = false;
      this.Close();
  }

请你帮助我好吗?

我猜你的问题是关于定时器的使用。

这两行具有相同的效果:mytimer.Enabled = true; 我的计时器开始();

您的程序所做的是设置计时器以在 6 秒后触发事件。 当它触发时,您可以设置录音、启动它并在几毫秒内停止它。

我的建议 - 不要触摸计时器。 它将每 6 秒触发一次事件。 使用 boolean 了解您是否正在录音。 当事件第一次触发时,您开始录制并相应地设置您的 boolean。 当事件第二次触发时,您停止录制并相应地设置您的 boolean。 您将拥有一个记录了最后 6 秒的文件。 如果您只希望事件触发一次,您可以在停止录制后停止计时器。 定时器不会再次触发事件,您可以关闭程序。

我不确定您是否正确设置了录音,但很明显您没有正确使用定时器。 使用控制台程序尝试一下,每次事件触发时您都在其中编写,以及您的 boolean 值是多少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM