Convert WasapiLoopbackCapture wav audio stream to MP3 file

前端 未结 2 451
时光说笑
时光说笑 2021-02-06 14:44

I am able to capture system audio which is generated by speaker with the help of WasapiLoopbackCapture (naudio). but the problem is it capture wav file and size of wav file very

相关标签:
2条回答
  • 2021-02-06 15:11

    Here's an example of using NAudio.Lame (in a console application) to capture data from sound card loopback and write direct to an MP3 file:

    using System;
    using NAudio.Lame;
    using NAudio.Wave;
    
    namespace MP3Rec
    {
        class Program
        {
            static LameMP3FileWriter wri;
            static bool stopped = false;
    
            static void Main(string[] args)
            {
                // Start recording from loopback
                IWaveIn waveIn = new WasapiLoopbackCapture();
                waveIn.DataAvailable += waveIn_DataAvailable;
                waveIn.RecordingStopped += waveIn_RecordingStopped;
                // Setup MP3 writer to output at 32kbit/sec (~2 minutes per MB)
                wri = new LameMP3FileWriter( @"C:\temp\test_output.mp3", waveIn.WaveFormat, 32 );
                waveIn.StartRecording();
    
                stopped = false;
    
                // Keep recording until Escape key pressed
                while (!stopped)
                {
                    if (Console.KeyAvailable)
                    {
                        var key = Console.ReadKey(true);
                        if (key != null && key.Key == ConsoleKey.Escape)
                            waveIn.StopRecording();
                    }
                    else
                        System.Threading.Thread.Sleep(50);
                }
    
                // flush output to finish MP3 file correctly
                wri.Flush();
                // Dispose of objects
                waveIn.Dispose();
                wri.Dispose();
            }
    
            static void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
            {
                // signal that recording has finished
                stopped = true;
            }
    
            static void waveIn_DataAvailable(object sender, WaveInEventArgs e)
            {
                // write recorded data to MP3 writer
                if (wri != null)
                    wri.Write(e.Buffer, 0, e.BytesRecorded);
            }
        }
    }
    

    At the moment the NAudio.Lame package on NuGet is compiled for x86 only, so make sure your application is set to target that platform.

    0 讨论(0)
  • 2021-02-06 15:24

    To convert the audio to MP3 on the fly, one of the easiest ways is to use the command line options that let you pass audio into LAME.exe via stdin. I describe how to do that in this article.

    You may also be interested that Corey Murtagh has created a LAME package for NAudio. I haven't tried it myself, but it looks like it should also do the job. Documentation is here.

    0 讨论(0)
提交回复
热议问题