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

时间:2018-11-20 19:28:43

标签: c# audio naudio

我正在使用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();
  }

能请你帮我吗?

0 个答案:

没有答案