public MemoryStream GetMp3Sample(int seconds, string filepath = "") { try { var stream = new MemoryStream(); // Start recording from loopback IWaveIn waveIn = new WasapiLoopbackCapture(); waveIn.DataAvailable += waveIn_DataAvailable; waveIn.RecordingStopped += waveIn_RecordingStopped; // Setup MP3 writer to output at 96kbit/sec writer = new LameMP3FileWriter(stream, waveIn.WaveFormat, LAMEPreset.ABR_96); _isRecording = true; waveIn.StartRecording(); // Wait for X seconds System.Threading.Thread.Sleep(seconds * 1000); waveIn.StopRecording(); // flush output to finish MP3 file correctly writer.Flush(); // Dispose of objects waveIn.Dispose(); writer.Dispose(); if (filepath != "") using (var file = new FileStream(filepath, FileMode.Create, FileAccess.Write)) stream.WriteTo(file); return stream; } catch (Exception) { throw; } }
private void FlushBufferToFile() { IsRecording = false; this.OnAudioData(new AudioDataEventArgs()); _prerecord.Clear(); _recordingEnd = DateTime.Now; var dirName = Options.GetActualOutputDir(); if (Options.CreateDateSubdirectories) { dirName = Path.Combine(dirName, _recordingEnd.Date.ToString("dd-MM-yy")); } if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } var fileName = "Record from " + _recordingBegin.ToString("dd-MM-yy HH:mm:ss") + " to " + _recordingEnd.ToString("dd-MM-yy HH:mm:ss"); fileName += ".mp3"; fileName = NormalizeFileName(fileName); fileName = Path.Combine(dirName, fileName); if (_recordingBegin != DateTime.MinValue) { var audioLengthMs = _recordingEnd.Subtract(_recordingBegin).TotalMilliseconds; // 27/01/16 don`t save empty audio (started by random sygnal pick) if (Math.Abs(audioLengthMs - Options.StopIntegrationTime - Options.PrerecordDuration) > Options.MinAudioLength) { try { //var phoneNumber = new Aon().RecognizePhoneNumber(Options.MicrophoneBitRate, // _recordingBufferStream.ToArray()); //if (!string.IsNullOrEmpty(phoneNumber)) //{ // var fileNameNoExt = Path.GetFileNameWithoutExtension(fileName); // fileNameNoExt = fileNameNoExt + "_" + phoneNumber; // var fileExt = Path.GetExtension(fileName); // fileName = NormalizeFileName(Path.Combine(Path.GetDirectoryName(fileName), // fileNameNoExt + fileExt)); //} _recordingBufferStream.Seek(0, SeekOrigin.Begin); using (var mp3File = new LameMP3FileWriter(fileName, _waveIn.WaveFormat, Options.OutputBitRate)) { _recordingBufferStream.CopyTo(mp3File); mp3File.Flush(); } OnAfterFlushToFile(new FileSystemEventArgs(WatcherChangeTypes.Created, dirName, fileName)); if (!string.IsNullOrEmpty(Options.AfterMp3FlushCommand)) { var cmd = Options.AfterMp3FlushCommand; try { var psi = new ProcessStartInfo(cmd, $@"""{fileName}"""); psi.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(psi); } catch (Exception e) { } } } catch (Exception e) { Debug.WriteLine(e.Message); } } } _recordingBufferStream = new MemoryStream(); _recordingBegin = DateTime.MinValue; _recordingEnd = DateTime.MinValue; }