【问题标题】:Recording with NAudio using C#使用 C# 使用 NAudio 进行录制
【发布时间】:2011-08-08 16:45:15
【问题描述】:

我正在尝试使用 NAudio 在 C# 中录制音频。在查看了 NAudio Chat Demo 之后,我使用了那里的一些代码进行记录。

代码如下:

using System;
using NAudio.Wave;

public class FOO
{
    static WaveIn s_WaveIn;

    static void Main(string[] args)
    {
        init();
        while (true) /* Yeah, this is bad, but just for testing.... */
            System.Threading.Thread.Sleep(3000);
    }

    public static void init()
    {
        s_WaveIn = new WaveIn();
        s_WaveIn.WaveFormat = new WaveFormat(44100, 2);

        s_WaveIn.BufferMilliseconds = 1000;
        s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
        s_WaveIn.StartRecording();
    }

    static void SendCaptureSamples(object sender, WaveInEventArgs e)
    {
        Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
    }
}

但是,没有调用 eventHandler。我正在使用 .NET 版本“v2.0.50727”并将其编译为:

csc file_name.cs /reference:Naudio.dll /platform:x86

【问题讨论】:

    标签: c# audio-recording naudio


    【解决方案1】:

    如果这是您的全部代码,那么您缺少message loop。所有 eventHandler 特定的事件都需要一个消息循环。您可以根据需要添加对ApplicationForm 的引用。

    这是一个使用Form的例子:

    using System;
    using System.Windows.Forms;
    using System.Threading;
    using NAudio.Wave;
    
    public class FOO
    {
        static WaveIn s_WaveIn;
    
        [STAThread]
        static void Main(string[] args)
        {
            Thread thread = new Thread(delegate() {
                init();
                Application.Run();
            });
    
            thread.Start();
    
            Application.Run();
        }
    
        public static void init()
        {
            s_WaveIn = new WaveIn();
            s_WaveIn.WaveFormat = new WaveFormat(44100, 2);
    
            s_WaveIn.BufferMilliseconds = 1000;
            s_WaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(SendCaptureSamples);
            s_WaveIn.StartRecording();
        }
    
        static void SendCaptureSamples(object sender, WaveInEventArgs e)
        {
            Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
        }
    }
    

    【讨论】:

    • 是的,缺少消息循环是问题所在。另一种解决方法是使用函数回调。
    • 如何将录制的数据保存到音频文件中?
    【解决方案2】:

    只需使用WaveInEvent 而不是WaveIn,代码就可以工作。然后处理发生在单独的线程上,而不是在控制台应用程序中不可用的窗口消息循环中。

    延伸阅读:
    https://github.com/naudio/NAudio/wiki/Understanding-Output-Devices#waveout-and-waveoutevent

    (该功能已添加in 2012,因此在提出问题时它不可用)

    【讨论】:

    • 以及如何将录制的消息保存到文件中? [代码] wave_in.StartRecording();玩(); wave_in.StopRecording(); [\code]
    猜你喜欢
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    相关资源
    最近更新 更多