NAudio-我无法覆盖wav文件

时间:2019-12-17 17:00:53

标签: c# file naudio recording wave

这是我的第一个问题,我完全是C#的新手,试图学习如何通过示例进行编码。

我的代码是测试笔记本电脑中存在的内部和外部麦克风。我可以使用一个列表框选择麦克风,该列表框显示系统中有多少个麦克风。

选择所需的麦克风进行测试后,我有两个按钮,一个用于录音,另一个用于播放。

   private void TesteDeFalantesMicrofone_Load(object sender, EventArgs e)
    {
        int microfonesAtivos = NAudio.Wave.WaveIn.DeviceCount;
        List<string> listaMicrofone = new List<string>();
        for (int microfoneAtivo = 0; microfoneAtivo < microfonesAtivos; microfoneAtivo++)
        {
            NAudio.Wave.WaveInCapabilities deviceInfo = NAudio.Wave.WaveIn.GetCapabilities(microfoneAtivo);
            listaMicrofone.Add(microfoneAtivo + ": " + deviceInfo.ProductName);
        }

        listBox1.DataSource = listaMicrofone;

        var outputFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Auto-OOBA");
        Directory.CreateDirectory(outputFolder);
        var outputFilePath = Path.Combine(outputFolder, "Gravação.wav");
        var file = outputFilePath;

        var waveIn = new WaveInEvent();
        var waveOut = new WaveOutEvent();

        WaveFileWriter writer = null;
        bool closing = false;

        button5.Click += (s, a) =>
        {
            waveIn.DeviceNumber = microfoneEscolhido;
            writer = new WaveFileWriter(outputFilePath, waveIn.WaveFormat);
            waveIn.StartRecording();
            button5.Enabled = false;
            button6.Enabled = true;
            button7.Enabled = false;
        };

        button6.Click += (s, a) =>
        {
            waveIn.StopRecording();
            button5.Enabled = true;
            button6.Enabled = false;
            button7.Enabled = true;
        };

            button7.Click += (s, a) =>
        {
            NAudio.Wave.WaveFileReader wave = new NAudio.Wave.WaveFileReader(outputFilePath);
            NAudio.Wave.DirectSoundOut output = new NAudio.Wave.DirectSoundOut();
            output.Init(new NAudio.Wave.WaveChannel32(wave));
            output.Play();
            output.Stop();
            output.Dispose();

            wave.Close();

            button5.Enabled = true;
            button6.Enabled = false;
        };

        waveIn.DataAvailable += (s, a) =>
        {
            writer.Write(a.Buffer, 0, a.BytesRecorded);
            if (writer.Position > waveIn.WaveFormat.AverageBytesPerSecond * 30)
            {
                waveIn.StopRecording();
            }
        };

        waveIn.RecordingStopped += (s, a) =>
        {
            writer?.Dispose();
            writer = null;
//          button6.Enabled = true;
//          buttonStop.Enabled = false;
            if (closing)
            {
                waveIn.Dispose();
            }
        };

    }

在上一次尝试中,我添加了wave.Close(),然后可以覆盖文件,但是我再也听不到录音了...

没有它,我得到:

  

System.IO.IOException:'进程无法访问文件   'C:\ Users \ saortech \ Desktop \ Auto-OOBA \Gravação.wav',因为它正在   由另一个进程使用。'

任何帮助将不胜感激。

最诚挚的问候!

0 个答案:

没有答案