public partial class RecordingForm : Form { IWaveIn waveIn; WaveFileWriter writer; string outputFilename; public RecordingForm() { InitializeComponent(); //LoadWasapiDevicesCombo(); } private void LoadWasapiDevicesCombo() { MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator(); MMDeviceCollection deviceCol = deviceEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active); Collection<MMDevice> devices = new Collection<MMDevice>(); foreach (MMDevice device in deviceCol) { devices.Add(device); } this.comboDevices.DataSource = devices; this.comboDevices.DisplayMember = "FriendlyName"; } private void buttonStartRecording_Click(object sender, EventArgs e) { if (waveIn == null) { if (outputFilename == null) { buttonSelectOutputFile_Click(sender, e); } if (outputFilename == null) { return; } waveIn = new WaveIn(); waveIn.WaveFormat = new WaveFormat(8000, 1); writer = new WaveFileWriter(outputFilename, waveIn.WaveFormat); waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable); waveIn.RecordingStopped += new EventHandler(waveIn_RecordingStopped); waveIn.StartRecording(); buttonStartRecording.Enabled = false; } } void waveIn_RecordingStopped(object sender, EventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler(waveIn_RecordingStopped), sender, e); } else { waveIn.Dispose(); waveIn = null; writer.Close(); writer = null; buttonStartRecording.Enabled = true; progressBar1.Value = 0; if (checkBoxAutoPlay.Checked) { Process.Start(outputFilename); } } } void waveIn_DataAvailable(object sender, WaveInEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler<WaveInEventArgs>(waveIn_DataAvailable), sender, e); } else { writer.WriteData(e.Buffer, 0, e.BytesRecorded); int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond); if (secondsRecorded >= 30) { StopRecording(); } else { progressBar1.Value = secondsRecorded; } } } void StopRecording() { Debug.WriteLine("StopRecording"); waveIn.StopRecording(); } private void buttonStopRecording_Click(object sender, EventArgs e) { if (waveIn != null) { StopRecording(); } } private void buttonSelectOutputFile_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "Select output file:"; saveFileDialog.Filter = "WAV Files (*.wav)|*.wav"; saveFileDialog.FileName = outputFilename; if (saveFileDialog.ShowDialog() == DialogResult.OK) { outputFilename = saveFileDialog.FileName; } } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)