Convert WasapiLoopbackCapture wav audio stream to MP3 file

前端 未结 2 450
时光说笑
时光说笑 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.

提交回复
热议问题