在控制台应用程序中使用NAudio录制麦克风音频

时间:2014-07-07 09:32:46

标签: c# audio-recording naudio

我的代码运行并创建了一个test.wav,但是这个文件包含了一些东西。我试图在控制台应用程序中运行此代码。请帮忙

        using System;
        using System.Media;
        using NAudio;
        using NAudio.Wave;

        class sound
        {
            public static void Main()
            {
                WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(0);
                Console.WriteLine("Now recording...");
                WaveInEvent waveSource = new WaveInEvent();
                waveSource.DeviceNumber = 0;
                waveSource.WaveFormat = new WaveFormat(16000, deviceInfo.Channels);

                //waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);

                string tempFile = (@"C:\Users\user\Desktop\test1.wav");
                WaveFileWriter waveFile = new WaveFileWriter(tempFile, waveSource.WaveFormat);
                waveSource.StartRecording();

            }

            //void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
            //{
            //    wavefile.WriteData(e.Buffer, 0, e.BytesRecorded);
            //}

        }

并且有人可以解释被评论的行是什么意思。我是编程的初学者。

当我编译程序时,它给出了2个错误: 错误1:非静态字段,方法或属性'sound.waveSource_DataAvailable(object,NAudio.Wave.WaveInEventArgs)'C:\ Users \ user \ Documents \ Visual Studio 2008 \ Projects \ sound \需要对象引用sound \ Program.cs 18 49 sound

错误2当前上下文中不存在名称'wavefile'C:\ Users \ user \ Documents \ Visual Studio 2008 \ Projects \ sound \ sound \ Program.cs 28 21 sound

2 个答案:

答案 0 :(得分:3)

显然StartRecording方法会启动一些捕获循环,定期引发DataAvailable事件以允许用户收集记录的数据。在示例代码中,事件句柄将记录的数据正确附加到文件tempFile。函数waveInStream_DataAvailablewaveFile都必须声明为static。

答案 1 :(得分:0)

试试这个:

using System;
using System.Media;
using NAudio;
using NAudio.Wave;

class sound
    {
        static WaveFileWriter waveFile;
        public static void Main()
        {
            //WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(0);
            Console.WriteLine("Now recording...");
            WaveInEvent waveSource = new WaveInEvent();
            //waveSource.DeviceNumber = 0;
            waveSource.WaveFormat = new WaveFormat(44100, 1);

            waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);

            string tempFile = (@"C:\Users\user\Desktop\test1.wav");
            waveFile = new WaveFileWriter(tempFile, waveSource.WaveFormat);
            waveSource.StartRecording();
            Console.WriteLine("Press enter to stop");
            Console.ReadLine();
            waveSource.StopRecording();
            waveFile.Dispose();
        }

        static void waveSource_DataAvailable(object sender, WaveInEventArgs e)
        {
            waveFile.WriteData(e.Buffer, 0, e.BytesRecorded);
        }

    }