C# recording audio based on audio in Console
1.
Install-package naudio -v 1.9.0
2.
using NAudio.Wave;
3.
public class NAudioHelper { public WaveInEvent mWavIn; public WaveFileWriter mWavWriter; public bool IsStoppedRecording { get; set; } = false; /// <summary> /// starting recording /// </summary> /// <param name="filePath"></param> public void StartRecord(string filePath) { mWavIn = new WaveInEvent(); mWavIn.DataAvailable += MWavIn_DataAvailable; mWavWriter = new WaveFileWriter(filePath, mWavIn.WaveFormat); mWavIn.StartRecording(); ConsoleKeyInfo cki = Console.ReadKey(true); while (cki.Key == ConsoleKey.Escape) { //Environment.Exit(0); StopRecord(); IsStoppedRecording = true; if(IsStoppedRecording) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Stopped recording!"); break; } } } /// <summary> /// stop recording /// </summary> public void StopRecord() { mWavIn?.StopRecording(); mWavIn?.Dispose(); mWavIn = null; mWavWriter?.Close(); mWavWriter = null; } private void MWavIn_DataAvailable(object sender, WaveInEventArgs e) { mWavWriter.Write(e.Buffer, 0, e.BytesRecorded); int secondsRecorded = (int)mWavWriter.Length / mWavWriter.WaveFormat.AverageBytesPerSecond; } } static void Main(string[] args) { NAudioDemo(); } static void NAudioDemo() { NAudioHelper recordHelper = new NAudioHelper(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Ready!"); Console.WriteLine("Enter Enter Key to start recording!"); ConsoleKeyInfo info = Console.ReadKey(true); bool isStarted = false; while (info.Key==ConsoleKey.Enter) { if (!isStarted) { string recordedFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".mp3"; Console.WriteLine("Start recording..."); Console.WriteLine("Press the Escape(Esc) key to quit: \n"); recordHelper.StartRecord(recordedFileName); isStarted = true; } } }