示例#1
0
        public void StopCapture()
        {
            _capture.Stop();
            if (!_writer.IsDisposed)
            {
                _writer.Dispose();
            }

            _capture.Dispose();
        }
示例#2
0
        public void Cleanup()
        {
            channelMemoryA?.Clear();
            channelMemoryB?.Clear();

            channelWriterA?.Dispose();
            channelWriterB?.Dispose();

            channelStreamA?.Dispose();
            channelStreamB?.Dispose();

            channelCapture?.Dispose();

            fileTimer?.Stop();
            fileTimer?.Dispose();
        }
示例#3
0
    /// <summary>
    /// Stop Recording
    /// </summary>
    /// <returns>Successful</returns>
    public bool Stop()
    {
        if (!isRecording)
        {
            return(false);
        }

        // Stop Capturing Audio
        if (recordAudio)
        {
            audioSource.Stop();

            if (audioSource != null)
            {
                audioSource.Dispose();
                audioSource = null;
            }

            if (audioFile != null)
            {
                audioFile.Dispose();
                audioFile = null;
            }
        }

        // Kill Timers
        StopTimers();

        status      = "Idle";
        isRecording = false;
        return(isRecording);
    }
示例#4
0
        //##########################################################################################################################################################################################################

        /// <summary>
        /// Save all samples to a new WAV file
        /// </summary>
        /// <param name="filepath">filepath of the new WAV file</param>
        public void SaveFile(string filepath)
        {
            if (Samples == null || format == null)
            {
                return;
            }

            if (!File.Exists(filepath))
            {
                FileStream stream = File.Create(filepath);
                stream.Close();
            }
            else
            {
                File.Delete(filepath);
            }

            WaveWriter writer = new WaveWriter(filepath, format);

            foreach (AudioSample s in Samples)
            {
                writer.WriteSample(s.Value);
            }
            writer.Dispose();
        }
示例#5
0
        public void Dispose()
        {
            if (_waveWriter != null)
            {
                _waveWriter.Dispose();
                _waveWriter = null;
            }

            if (_notificationSource != null)
            {
                _notificationSource.Dispose();
                _notificationSource = null;
            }

            if (_waveSource != null)
            {
                _waveSource.Dispose();
                _waveSource = null;
            }

            if (_soundInSource != null)
            {
                _soundInSource.Dispose();
                _soundInSource = null;
            }

            if (_capture != null)
            {
                _capture.Dispose();
                _capture = null;
            }
        }
示例#6
0
        private void StopRecording()
        {
            m_capture.Stop();
            m_capture.Dispose();

            m_ww.Dispose();
        }
示例#7
0
    public bool stopRecording()
    {
        bool isStopped = false;

        if (System.Web.HttpContext.Current.Session[ww] != null && System.Web.HttpContext.Current.Session[wc] != null)
        {
            capture = (WasapiCapture)System.Web.HttpContext.Current.Session[wc];
            w       = (WaveWriter)System.Web.HttpContext.Current.Session[ww];
            //stop recording
            capture.Stop();
            w.Dispose();
            w = null;
            capture.Dispose();
            capture = null;

            System.Web.HttpContext.Current.Session[ww] = null;
            System.Web.HttpContext.Current.Session[wc] = null;
            //Label1.Text = "Stopped";
        }
        else
        {
            isStopped = true;
        }

        return(isStopped);
    }
示例#8
0
        private void Stop()
        {
            if (!recording)
            {
                return;
            }

            outputCapture.Stop();
            inputCapture.Stop();
            process.StandardInput.Write('q');
            process.WaitForExit(1000);
            process.Close();

            groupBox1.Enabled = true;
            groupBox2.Enabled = true;
            groupBox3.Enabled = true;
            groupBox4.Enabled = true;

            if (outputWaveWriter != null)
            {
                outputWaveWriter.Dispose();
            }

            if (inputWaveWriter != null)
            {
                inputWaveWriter.Dispose();
            }

            outputCapture.Dispose();

            inputCapture.Dispose();

            recording = false;
        }
示例#9
0
        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (!recording)
            {
                btnStartStop.Text = "Stop";

                writer = new WaveWriter(textOutputFile.Text, capture.WaveFormat);
                capture.Start();
                recording = true;

                recordTime              = new TimeSpan();
                recordTimer.Enabled     = true;
                btnSelectDevice.Enabled = false;

                Console.WriteLine("Started recording");
            }
            else
            {
                btnStartStop.Text = "Start!";

                capture.Stop();
                writer.Dispose();
                recording = false;

                recordTimer.Enabled     = false;
                btnSelectDevice.Enabled = true;

                Console.WriteLine("Stopped recording");
            }
        }
示例#10
0
 /// <summary>
 /// Decode File
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public bool DecodeFile()
 {
     try {
         if (!string.IsNullOrEmpty(CurrentFile))
         {
             _chunkSize = 4096;                          // Set Default Chunk Size
             if (CurrentFile.ToLower().Contains(".mp3")) // Check Mp3
             {
                 if (System.IO.File.Exists(CurrentFile)) // Check File Exists
                 {
                     CurrentFileName = System.IO.Path.GetFileName(CurrentFile);
                     using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) {                  // Create Mp3 Stream
                         _mp3Stream      = mp3Stream;                                               // Set Mp3 Stream
                         _bytes          = new byte[mp3Stream.Length];                              // Set Bytes
                         _totalBytes     = mp3Stream.Length;                                        // Set Total Bytes
                         _numBytesToRead = _totalBytes;                                             // Set Num Bytes to Read
                         _numBytesRead   = 0;                                                       // Set Num Bytes Read to 0
                         using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer
                             _writer = writer;                                                      // Set Writer
                             while (_numBytesToRead > 0)                                            // Loop through Chunks
                             {
                                 if (_chunkSize > _numBytesToRead)                                  // Check Progress isn't greater than remaining bytes
                                 {
                                     _chunkSize = 1;                                                // Check a chunk at a time
                                 }
                                 var t = new Thread(ReadDecodeChunk);
                                 t.Start();
                                 if (!t.Join(1500))
                                 {
                                     t.Abort();           // Oops! We read 1 too many bytes! Lets stop trying, we got everything.
                                     _numBytesToRead = 0; // This should take us out of the loop soon
                                 }
                                 if (_readDecodeResult == 0)
                                 {
                                     break;
                                 }
                                 _numBytesRead   += _readDecodeResult;
                                 _numBytesToRead -= _readDecodeResult;
                                 _percent         = ((int)_numBytesRead * 100 / _totalBytes);
                                 if (PercentChanged != null)
                                 {
                                     PercentChanged(_percent);
                                 }
                             }
                             _writer = null;
                             writer.Close();
                             writer.Dispose();
                         }
                         _numBytesToRead = _bytes.Length;
                         _mp3Stream      = null;
                     }
                 }
             }
         }
         return(true);
     } catch {
         throw;
     }
 }
示例#11
0
        public void StopRecording()
        {
            WaveIn?.StopRecording();
            WaveIn?.Dispose();
            WaveIn = null;

            WaveWriter?.Dispose();
            WaveWriter = null;
        }
示例#12
0
 private void stopRecording()
 {
     if (writer != null && capture != null)
     {
         capture.Stop();
         writer.Dispose();
         capture.Dispose();
     }
 }
示例#13
0
        public void StopRecording()
        {
            areRecording = false;
            outputCapture.DataAvailable -= WriteOutputData;
            inputCapture.DataAvailable  -= WriteInputData;

            outputWave.Dispose();
            inputWave.Dispose();
        }
示例#14
0
        public void Stop()
        {
            if (_isStarted)
            {
                _waveWriter.Dispose();
                _waveWriter = null;
            }

            _isStarted = false;
        }
示例#15
0
        private void OnTimedEvent(object sender, ElapsedEventArgs e)
        {
            //stop recording
            capture.Stop();
            aTimer.Enabled = false;
            writer.Dispose();
            capture.Dispose();

            Console.WriteLine("Zakończono nagrywanie.");
        }
示例#16
0
 public void Stop()
 {
     if (_soundIn.RecordingState == RecordingState.Stopped)
     {
         return;
     }
     _soundIn.Stop();
     _waveWriter.Dispose();
     _waveWriter = null;
 }
示例#17
0
        private void OnFinishedRecordingEvent(object sender, ElapsedEventArgs e)
        {
            _capture.Stop();                  //stop recording

            _recordFileTimer.Enabled = false; //timer disabled

            _writer.Dispose();
            _capture.Dispose();

            Console.WriteLine("now really finished");
        }
示例#18
0
        public static async Task RecordSample()
        {
            //create a new soundIn instance
            var soundIn = new WasapiCapture();

            //optional: set some properties
            //soundIn.Device = ...
            //...
            soundIn.Device = new DeviceService().InputDevices().First();
            soundIn.Initialize();

            var waveWriter = new WaveWriter(@"C:\Users\Cedric Lampron\Desktop\Test Record\dump.wav", soundIn.WaveFormat);;

            await Task.Run(() =>
            {
                //create a SoundSource around the the soundIn instance
                //this SoundSource will provide data, captured by the soundIn instance
                var soundInSource = new SoundInSource(soundIn)
                {
                    FillWithZeros = false
                };

                //create a source, that converts the data provided by the
                //soundInSource to any other format
                //in this case the "Fluent"-extension methods are being used
                IWaveSource convertedSource = soundInSource
                                              .ToStereo()             //2 channels (for example)
                                              .ChangeSampleRate(8000) // 8kHz sample rate
                                              .ToSampleSource()
                                              .ToWaveSource(16);      //16 bit pcm

                //register an event handler for the DataAvailable event of
                //the soundInSource
                //Important: use the DataAvailable of the SoundInSource
                //If you use the DataAvailable event of the ISoundIn itself
                //the data recorded by that event might won't be available at the
                //soundInSource yet
                soundInSource.DataAvailable += (s, e) =>
                {
                    waveWriter.Write(e.Data, e.Offset, e.ByteCount);
                };

                //we've set everything we need -> start capturing data
                soundIn.Start();
            });

            await Task.Delay(5000);

            soundIn.Stop();
            waveWriter.Dispose();
            waveWriter = null;
            soundIn.Dispose();
            soundIn = null;
        }
示例#19
0
        /// <summary>
        /// ran after recording timer finishes, stops WasapiLoopbackCapture capturing, disposes audio writer, disables record timer
        /// </summary>
        private void OnFinishedRecordingEvent(object sender, ElapsedEventArgs e)
        {
            _log.Called(sender.ToString(), string.Empty);

            try
            {
                _capture.Stop();                  //stop recording

                _recordFileTimer.Enabled = false; //timer disabled

                _writer.Dispose();
            }
            catch
            {
                _log.Error("Problems when finishing recording.");
            }
        }
示例#20
0
        public virtual void RecordAudioFile()
        {
            string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string wavFile          = Path.Combine(currentDirectory, "recording.wav");

            _jackIn.Initialize();
            WaveWriter writer = new WaveWriter(wavFile, _jackIn.WaveFormat);

            _jackIn.DataAvailable += (sender, args) => {
                writer.Write(args.Data, 0, args.ByteCount);
            };
            _jackIn.Stopped += (sender, e) => {
                writer.Dispose();
                long fileSize = new FileInfo(wavFile).Length;
                Assert.AreNotEqual(0, fileSize);
            };
            _jackIn.Start();
            Thread.Sleep(100);
            _jackIn.Stop();
        }
示例#21
0
        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (!recording)
            {
                btnStartStop.Text = "Stop";

                /* clear the existing file */
                sw = new StreamWriter(textOutputFile.Text);
                sw.Dispose();

                writer = new WaveWriter(textOutputFile.Text, capture.WaveFormat);
                //writer = new WaveWriter(streamBuffer, capture.WaveFormat);
                //sw = new StreamWriter(textOutputFile.Text);


                capture.Start();
                recording = true;

                recordTime              = new TimeSpan();
                recordTimer.Enabled     = true;
                btnSelectDevice.Enabled = false;

                Console.WriteLine("Started recording");
            }
            else
            {
                btnStartStop.Text = "Start!";

                capture.Stop();
                writer.Dispose();
                //sw.Dispose();
                recording = false;

                recordTimer.Enabled     = false;
                btnSelectDevice.Enabled = true;

                output_to_file();

                Console.WriteLine("Stopped recording");
            }
        }
        private void OnRemoteVoiceAdded(RemoteVoiceLink remoteVoiceLink)
        {
            int    bitsPerSample = 32;
            string filePath      = this.GetFilePath(remoteVoiceLink);

            if (this.Logger.IsInfoEnabled)
            {
                this.Logger.LogInfo("Incoming stream, output file path: {0}", filePath);
            }
            WaveWriter waveWriter = new WaveWriter(filePath, new WaveFormat(remoteVoiceLink.Info.SamplingRate, bitsPerSample, remoteVoiceLink.Info.Channels));

            remoteVoiceLink.FloatFrameDecoded  += f => { waveWriter.WriteSamples(f.Buf, 0, f.Buf.Length); };
            remoteVoiceLink.RemoteVoiceRemoved += () =>
            {
                if (this.Logger.IsInfoEnabled)
                {
                    this.Logger.LogInfo("Remote voice stream removed: Saving wav file.");
                }
                waveWriter.Dispose();
            };
        }
示例#23
0
        public static void StopRecording()
        {
            // Stop recording
            capture.Stop();

            // Dispose respective writers (for WAV, Dispose() writes header)
            switch (writerType)
            {
            case WriterType.EncoderWriter:
                encoderWriter.Dispose();
                break;

            case WriterType.WaveWriter:
                waveWriter.Dispose();
                break;
            }

            // Dispose of other objects
            stereoSource.Dispose();
            wasapiCaptureSource.Dispose();
            capture.Dispose();
        }
示例#24
0
        public void RecSoundStop(bool isDeleteWav)
        {
            if (w != null && capture != null)
            {
                capture.Stop();
                w.Dispose();
                w = null;
                capture.Dispose();
                capture = null;

                LogIt("began converting to mp3");
                Task task1 = Task.Factory.StartNew(() => ConvertToMP3(_outputWaveName));
                task1.Wait();
                LogIt(string.Format("converting finished to {0}", _outputMp3Name));

                if (isDeleteWav)
                {
                    File.Delete(_outputWaveName);
                    LogIt(string.Format("File {0} deleted", _outputWaveName));
                }
                LogIt(string.Format("recording {0} stopped", _outputWaveName));
            }
        }
示例#25
0
 /// <summary>
 /// Decode File
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public bool DecodeFile()
 {
     try {
         if (!string.IsNullOrEmpty(CurrentFile)) {
             _chunkSize = 4096; // Set Default Chunk Size
             if (CurrentFile.ToLower().Contains(".mp3")) { // Check Mp3
                 if (System.IO.File.Exists(CurrentFile)) { // Check File Exists
                     CurrentFileName = System.IO.Path.GetFileName(CurrentFile);
                     using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) { // Create Mp3 Stream
                         _mp3Stream = mp3Stream; // Set Mp3 Stream
                         _bytes = new byte[mp3Stream.Length]; // Set Bytes
                         _totalBytes = mp3Stream.Length; // Set Total Bytes
                         _numBytesToRead = _totalBytes; // Set Num Bytes to Read
                         _numBytesRead = 0; // Set Num Bytes Read to 0
                         using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer
                             _writer = writer; // Set Writer
                             while (_numBytesToRead > 0) { // Loop through Chunks
                                 if (_chunkSize > _numBytesToRead) { // Check Progress isn't greater than remaining bytes
                                     _chunkSize = 1; // Check a chunk at a time
                                 }
                                 var t = new Thread(ReadDecodeChunk);
                                 t.Start();
                                 if (!t.Join(1500)) {
                                     t.Abort(); // Oops! We read 1 too many bytes! Lets stop trying, we got everything.
                                     _numBytesToRead = 0; // This should take us out of the loop soon
                                 }
                                 if (_readDecodeResult == 0) {
                                     break;
                                 }
                                 _numBytesRead += _readDecodeResult;
                                 _numBytesToRead -= _readDecodeResult;
                                 _percent = ((int)_numBytesRead * 100 / _totalBytes);
                                 if (PercentChanged != null) {
                                     PercentChanged(_percent);
                                 }
                             }
                             _writer = null;
                             writer.Close();
                             writer.Dispose();
                         }
                         _numBytesToRead = _bytes.Length;
                         _mp3Stream = null;
                     }
                 }
             }
         }
         return true;
     } catch {
         throw;
     }
 }
示例#26
0
 public void Dispose()
 {
     _waveWriter?.Dispose();
 }
示例#27
0
 public void Dispose()
 {
     _waveWriter?.Dispose();
     _isStarted  = false;
     _waveWriter = null;
 }
示例#28
0
        public void Record(string deviceName, string audioFilePath = @"C:\Temp\output.wav")
        {
            _timer = new Stopwatch();
            _timer.Start();

            // choose the capture mod
            CaptureMode captureMode = CaptureMode.LoopbackCapture;
            DataFlow    dataFlow    = captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render;

            //select the device:
            var devices = MMDeviceEnumerator.EnumerateDevices(dataFlow, DeviceState.Active);

            if (!devices.Any())
            {
                Console.WriteLine("### No devices found.");
                return;
            }

            Console.WriteLine($"### Using device {deviceName}");
            var device = devices.First(d => d.FriendlyName.Equals(deviceName));

            //start recording
            //create a new soundIn instance
            _soundIn = captureMode == CaptureMode.Capture
                ? new WasapiCapture()
                : new WasapiLoopbackCapture();


            //optional: set some properties
            _soundIn.Device = device;


            //initialize the soundIn instance
            _soundIn.Initialize();

            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            SoundInSource soundInSource = new SoundInSource(_soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            _convertedSource = soundInSource
                               .ChangeSampleRate(SampleRate) // sample rate
                               .ToSampleSource()
                               .ToWaveSource(BitsPerSample); //bits per sample

            //channels...
            _convertedSource = _convertedSource.ToMono();

            //create a new wavefile
            _waveWriter = new WaveWriter(audioFilePath, _convertedSource.WaveFormat);

            //register an event handler for the DataAvailable event of
            //the soundInSource
            //Important: use the DataAvailable of the SoundInSource
            //If you use the DataAvailable event of the ISoundIn itself
            //the data recorded by that event might won't be available at the
            //soundInSource yet
            soundInSource.DataAvailable += (s, e) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                byte[] buffer = new byte[_convertedSource.WaveFormat.BytesPerSecond / 2];
                int    read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = _convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                {
                    //write the read data to a file
                    // ReSharper disable once AccessToDisposedClosure
                    _waveWriter.Write(buffer, 0, read);
                }
            };

            //we've set everything we need -> start capturing data
            _soundIn.Start();
            Console.WriteLine($"### RECORDING {audioFilePath}");

            while (_timer.ElapsedMilliseconds / 1000 < 15 && _timer.IsRunning)
            {
                Thread.Sleep(500);
            }

            Console.WriteLine("### STOP RECORDING");
            _soundIn.Stop();
            _timer.Stop();

            _waveWriter.Dispose();
            _convertedSource.Dispose();
            _soundIn.Dispose();

            AudioFileCaptured?.Invoke(this, new AudioRecorderEventArgs()
            {
                AudioFilePath = audioFilePath
            });
        }
示例#29
0
        //***********************************************************************************************************************************************************************************************************

        /// <summary>
        /// Stop a record
        /// </summary>
        public async void StopRecord()
        {
            try
            {
                if (RecordState == RecordStates.STOPPED)
                {
                    return;
                }

                if (_capture != null)
                {
                    try
                    {
                        _capture.Stop();
                        _capture.Dispose();
                    }
                    catch (Exception ex)
                    {
                        _logHandle.Report(new LogEventError("Error while stopping record: " + ex.Message));
                    }

                    _silenceOut.Stop();
                }
                if (_silenceOut != null)
                {
                    _silenceOut.Stop(); _silenceOut.Dispose();
                }
                if (_wavWriter != null)
                {
                    _wavWriter.Dispose();
                }
                _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") stopped."));

                if (System.IO.File.Exists(FileStrWAV))      //Delete too short records
                {
                    if (WasRecordPaused && RecorderRecSettings.DeletePausedRecords)
                    {
                        System.IO.File.Delete(FileStrWAV);
                        DirectoryManager.DeleteEmptyFolders(RecorderRecSettings.BasePath);
                        _logHandle.Report(new LogEventWarning("Record (\"" + TrackInfo?.TrackName + "\") deleted, because it was paused during record and DeletePausedRecords setting is enabled."));
                        RecordState = RecordStates.STOPPED;
                        return;
                    }

                    TimeSpan wavLength = TimeSpan.Zero;

                    try
                    {
                        FileInfo fileInfo = new FileInfo(FileStrWAV);
                        if (fileInfo.Length > 44)       //"Empty" files are 44 bytes big
                        {
                            IWaveSource wavSource = new WaveFileReader(FileStrWAV);
                            wavLength = wavSource.GetLength();
                            wavSource?.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        wavLength = TimeSpan.Zero;
                        _logHandle.Report(new LogEventError("Error while stopping record: " + ex.Message));
                    }

                    if (TrackInfo?.Duration > TimeSpan.Zero && (wavLength < (TrackInfo?.Duration - AllowedDifferenceToTrackDuration) || wavLength > (TrackInfo?.Duration + AllowedDifferenceToTrackDuration)))
                    {
                        System.IO.File.Delete(FileStrWAV);
                        DirectoryManager.DeleteEmptyFolders(RecorderRecSettings.BasePath);
                        _logHandle.Report(new LogEventWarning("Record (\"" + TrackInfo?.TrackName + "\") deleted, because of wrong length (Length = " + wavLength.ToString(@"hh\:mm\:ss\.fff") + " s, Expected Range = [" + (TrackInfo?.Duration - AllowedDifferenceToTrackDuration).Value.ToString(@"hh\:mm\:ss\.fff") + ", " + (TrackInfo?.Duration + AllowedDifferenceToTrackDuration).Value.ToString(@"hh\:mm\:ss\.fff") + "])."));
                        RecordState = RecordStates.STOPPED;
                        return;
                    }
                }

                if (!System.IO.File.Exists(FileStrWAV))
                {
                    RecordState = RecordStates.STOPPED;
                    return;
                }

                await Task.Run(() =>
                {
                    if (NormalizeWAVFile(FileStrWAV) == false)
                    {
                        RecordState = RecordStates.STOPPED; return;
                    }
                    _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") normalized."));

                    RecorderPostSteps?.Invoke(this, new EventArgs());

                    if (RecorderRecSettings.RecordFormat == RecordFormats.WAV_AND_MP3)
                    {
                        if (ConvertWAVToMP3(FileStrWAV, FileStrMP3) == false)
                        {
                            RecordState = RecordStates.STOPPED; return;
                        }
                        _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") converted to MP3."));
                    }
                    else if (RecorderRecSettings.RecordFormat == RecordFormats.MP3)
                    {
                        if (ConvertWAVToMP3(FileStrWAV, FileStrMP3) == false)
                        {
                            RecordState = RecordStates.STOPPED; return;
                        }
                        if (System.IO.File.Exists(FileStrWAV))
                        {
                            System.IO.File.Delete(FileStrWAV);
                        }
                        _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") converted to MP3 and WAV deleted."));
                    }

                    AddTrackTags(FileStrWAV, TrackInfo);
                    AddTrackTags(FileStrMP3, TrackInfo);
                    _logHandle.Report(new LogEventInfo("Record (\"" + TrackInfo?.TrackName + "\") tagged."));

                    RecordState = RecordStates.STOPPED;
                    OnRecorderPostStepsFinished?.Invoke(this, new EventArgs());
                });
            }
            catch (Exception ex)
            {
                _logHandle.Report(new LogEventError("Error while stopping record: " + ex.Message));
                RecordState = RecordStates.STOPPED;
            }
        }
示例#30
0
        private void MIDIConversionTbT(Control Form, Panel ThreadsPanel, String OPath)
        {
            try
            {
                Status = "prep";
                Int32      MT = Properties.Settings.Default.MultiThreadedMode ? Properties.Settings.Default.MultiThreadedLimitV : 1;
                WaveFormat WF = new WaveFormat(Properties.Settings.Default.Frequency, 32, 2, AudioEncoding.IeeeFloat);

                // Initialize BASS
                Debug.PrintToConsole("ok", "Initializing BASS...");
                if (!Bass.BASS_Init(0, WF.SampleRate, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero))
                {
                    throw new Exception("Unable to initialize BASS!");
                }

                LoadSoundFonts();

                foreach (MIDI MFile in Program.MIDIList)
                {
                    MultiStreamMerger MSM = new MultiStreamMerger(WF);

                    if (StopRequested)
                    {
                        Debug.PrintToConsole("ok", "Stop requested. Stopping foreach loop...");
                        break;
                    }

                    MDV.SetTotalTracks(MFile.Tracks);
                    MDV.ResetCurrentTrack();

                    // Begin conversion
                    Status = "mconv";

                    try
                    {
                        CTS = new CancellationTokenSource();
                        Debug.PrintToConsole("ok", String.Format("Preparing loop... MaxDegreeOfParallelism = {0}", MT));

                        ParallelFor(0, MFile.Tracks, MT, CTS.Token, T =>
                        {
                            if (StopRequested)
                            {
                                Debug.PrintToConsole("ok", "Stop requested. Stopping Parallel.For...");
                                //LS.Stop();
                                return;
                            }

                            if (MFile.NoteCount > 0)
                            {
                                TrackThreadStatus Trck = new TrackThreadStatus(T);
                                Trck.Dock = DockStyle.Top;
                                ThreadsPanel.Invoke((MethodInvoker) delegate
                                {
                                    Debug.PrintToConsole("ok", "Added TrackThreadStatus control for MIDI.");
                                    ThreadsPanel.Controls.Add(Trck);
                                });

                                ConvertWorker Worker = new ConvertWorker(MFile.GetSingleTrackTimeBased(T), MFile.TimeLength.TotalSeconds);
                                ISampleWriter Writer;
                                WaveWriter SDestination = null;
                                FileStream SFOpen       = null;
                                if (Properties.Settings.Default.PerTrackSeparateFiles)
                                {
                                    // Check if we need to export each track to a file
                                    String Folder = OPath;
                                    if (Properties.Settings.Default.PerTrackSeparateFiles)
                                    {
                                        // We do, create folder
                                        Folder += String.Format("\\{0}\\", Path.GetFileNameWithoutExtension(MFile.Name));

                                        if (!Directory.Exists(Folder))
                                        {
                                            Directory.CreateDirectory(Folder);
                                        }
                                    }
                                    else
                                    {
                                        Folder += " ";
                                    }

                                    // Prepare the filename
                                    String SOutputDir = String.Format("{0}Track {1}.{2}",
                                                                      Folder, T, Properties.Settings.Default.Codec);

                                    // Check if file already exists
                                    if (File.Exists(SOutputDir))
                                    {
                                        SOutputDir = String.Format("{0}Track {1} - {2}.{3}",
                                                                   Folder, T, DateTime.Now.ToString("dd-MM-yyyy HHmmsstt"), Properties.Settings.Default.Codec);
                                    }

                                    Debug.PrintToConsole("ok", String.Format("{0} - Output file: {1}", T, SOutputDir));

                                    SFOpen       = File.Open(SOutputDir, FileMode.Create);
                                    SDestination = new WaveWriter(SFOpen, WF);
                                    Writer       = new WaveSampleWriter(SDestination);
                                }
                                else
                                {
                                    Writer = MSM.GetWriter();
                                }

                                Task ConvThread = Task.Run(() =>
                                {
                                    Worker.Convert(Writer, WF, false, CTS.Token);
                                });

                                while (!ConvThread.IsCompleted)
                                {
                                    if (StopRequested)
                                    {
                                        break;
                                    }

                                    Trck.Invoke((MethodInvoker) delegate
                                    {
                                        Trck.UpdatePB(Convert.ToInt32(Math.Round(Worker.Progress * 100)));
                                    });

                                    Thread.Sleep(10);
                                }

                                ConvThread.Wait();

                                if (SDestination != null)
                                {
                                    SDestination.Dispose();
                                }
                                if (SFOpen != null)
                                {
                                    SFOpen.Dispose();
                                }

                                ThreadsPanel.Invoke((MethodInvoker) delegate
                                {
                                    Debug.PrintToConsole("ok", String.Format("{0} - Removed TrackThreadStatus control for MIDI.", T));
                                    ThreadsPanel.Controls.Remove(Trck);
                                });

                                if (!StopRequested)
                                {
                                    MDV.AddTrack();
                                }
                            }
                        });
                    }
                    catch (OperationCanceledException) { }
                    finally { CTS.Dispose(); CTS = null; }

                    if (StopRequested)
                    {
                        break;
                    }
                    else
                    {
                        MDV.AddValidMIDI();
                    }

                    // Time to save the file
                    String OutputDir = String.Format("{0}\\{1}.{2}",
                                                     OPath, Path.GetFileNameWithoutExtension(MFile.Name), Properties.Settings.Default.Codec);

                    // Check if file already exists
                    if (File.Exists(OutputDir))
                    {
                        OutputDir = String.Format("{0}\\{1} - {2}.{3}",
                                                  OPath, Path.GetFileNameWithoutExtension(MFile.Name),
                                                  DateTime.Now.ToString("dd-MM-yyyy HHmmsstt"), Properties.Settings.Default.Codec);
                    }

                    Debug.PrintToConsole("ok", String.Format("Output file: {0}", OutputDir));

                    // Reset MSM position
                    MSM.Position = 0;

                    // Prepare wave source
                    IWaveSource MStream;
                    if (Properties.Settings.Default.LoudMax)
                    {
                        Debug.PrintToConsole("ok", "LoudMax enabled.");
                        AntiClipping BAC = new AntiClipping(MSM, 0.1);
                        MStream = BAC.ToWaveSource(32);
                    }
                    else
                    {
                        MStream = MSM.ToWaveSource(32);
                    }

                    FileStream FOpen       = File.Open(OutputDir, FileMode.Create);
                    WaveWriter Destination = new WaveWriter(FOpen, WF);
                    Debug.PrintToConsole("ok", "Output file is open.");

                    Int32  FRead   = 0;
                    byte[] FBuffer = new byte[1024 * 16];

                    Status = "aout";
                    Debug.PrintToConsole("ok", String.Format("Writing data for {0} to disk...", OutputDir));
                    while ((FRead = MStream.Read(FBuffer, 0, FBuffer.Length)) != 0)
                    {
                        Destination.Write(FBuffer, 0, FRead);
                    }
                    Debug.PrintToConsole("ok", String.Format("Done writing {0}.", OutputDir));

                    Destination.Dispose();
                    FOpen.Dispose();
                }

                FreeSoundFonts();

                Debug.PrintToConsole("ok", "BASS freed.");
                Bass.BASS_Free();
            }
            catch (Exception ex)
            {
                Status  = "crsh";
                StError = String.Format("The converter encountered an error during the conversion process.\nError: {0}", ex.Message.ToString());
                IsCrash = true;

                Debug.PrintToConsole("err", String.Format("{0} - {1}", ex.InnerException.ToString(), ex.Message.ToString()));
            }

            if (!StopRequested && !IsCrash)
            {
                Form.Invoke((MethodInvoker) delegate { ((Form)Form).Close(); });
            }
        }
示例#31
0
        void Record(int channel)
        {
            state[channel].Disposable = Disposable.Empty;

            //create a new soundIn instance
            ISoundIn soundIn = new WasapiCapture();

            //optional: set some properties
            //soundIn.Device = ...
            //...

            //initialize the soundIn instance
            soundIn.Initialize();

            //create a SoundSource around the the soundIn instance
            //this SoundSource will provide data, captured by the soundIn instance
            var soundInSource = new SoundInSource(soundIn)
            {
                FillWithZeros = false
            };

            //create a source, that converts the data provided by the
            //soundInSource to any other format
            //in this case the "Fluent"-extension methods are being used
            var convertedSource = soundInSource
                                  .ToStereo()             //2 channels (for example)
                                  .ChangeSampleRate(8000) // 8kHz sample rate
                                  .ToSampleSource()
                                  .ToWaveSource(16);      //16 bit pcm

            //register an event handler for the DataAvailable event of
            //the soundInSource
            //Important: use the DataAvailable of the SoundInSource
            //If you use the DataAvailable event of the ISoundIn itself
            //the data recorded by that event might won't be available at the
            //soundInSource yet


            var waveWriter = new WaveWriter(channelFile(channel), convertedSource.WaveFormat);

            soundInSource.DataAvailable += (s, e) =>
            {
                //read data from the converedSource
                //important: don't use the e.Data here
                //the e.Data contains the raw data provided by the
                //soundInSource which won't have your target format
                var buffer = new byte[convertedSource.WaveFormat.BytesPerSecond / 2];
                int read;

                //keep reading as long as we still get some data
                //if you're using such a loop, make sure that soundInSource.FillWithZeros is set to false
                while ((read = convertedSource.Read(buffer, 0, buffer.Length)) > 0)
                {
                    //your logic follows here
                    //for example: stream.Write(buffer, 0, read);
                    waveWriter.Write(buffer, 0, read);
                }
            };

            //we've set everything we need -> start capturing data
            soundIn.Start();
            state[channel].Disposable = Disposable.Create(() =>
            {
                soundIn.Stop();
                waveWriter.Dispose();
            });
        }