static void Main(string[] args)
        {
            // Setup MP3 writer to output at 32kbit/sec (~2 minutes per MB)
            wri = new LameMP3FileWriter(@"C:\temp\test_output.mp3", waveIn.WaveFormat, 32);
            // Start recording from loopback
            IWaveIn waveIn = new WasapiLoopbackCapture();

            waveIn.DataAvailable    += waveIn_DataAvailable;
            waveIn.RecordingStopped += waveIn_RecordingStopped;
            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();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Send buffer to disk
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Data contaning the buffer values</param>
        private void DataAvailable(object sender, WaveInEventArgs e)
        {
#if DEBUG
            Console.WriteLine("Bytes recorded: {0}", e.BytesRecorded);
#endif
            string fileName = string.Format("{0}.mp3", DateTime.Now.Ticks);

            if (options.WorkingDirectory != null)
            {
                fileName = Path.Combine(options.WorkingDirectory, fileName);
            }

            var writter = new LameMP3FileWriter(fileName, waveFormat, (int)RecordingBitRate.BITRATE_128);

            //Create a new task/thread separately to save this buffer to disk, avoid thread blockage at all cost
            Task.Factory.StartNew(() => {
                writter.WriteAsync(e.Buffer, 0, e.BytesRecorded)
                .ContinueWith(x => {
                    writter.Flush();
                    writter.Dispose();
                    writter = null;
#if DEBUG
                    Console.WriteLine("File written: {0}", fileName);
#endif
                    //TODO: report back to the cloud server that this service is running, index the fileChunk, upload to cloud storage
                });
            }, TaskCreationOptions.LongRunning);
        }
Exemplo n.º 3
0
        //public static void WavToMp3File(ref MemoryStream ms, string savetofilename)
        public static void WavToMp3File(string inputWavFile)
        {
            var outputFile = Path.Combine(
                Path.GetDirectoryName(inputWavFile),
                Path.GetFileNameWithoutExtension(inputWavFile) + ".mp3");

            using (var rdr = new WaveFileReader(inputWavFile))
                using (var wtr = new LameMP3FileWriter(outputFile, rdr.WaveFormat, LAMEPreset.STANDARD))
                {
                    //rdr.CopyTo(wtr);
                    int size = 128;

                    while (rdr.Position < rdr.Length)
                    {
                        if (rdr.Length - rdr.Position < size)
                        {
                            size = (int)rdr.Length - (int)rdr.Position;
                        }

                        byte[] buffer = new byte[size];
                        var    r      = rdr.Read(buffer, 0, size);
                        wtr.Write(buffer, 0, size);
                    }

                    wtr.Flush();
                }
        }
Exemplo n.º 4
0
 //Окончание записи
 private void waveIn_RecordingStopped(object sender, EventArgs e)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new EventHandler(waveIn_RecordingStopped), sender, e);
     }
     else
     {
         _www.Dispose();
         _www = null;
         _writer.Close();
         _writer.Dispose();
         try
         {
             using (var reader = new AudioFileReader(_writer.Filename))
             {
                 using (var write = new LameMP3FileWriter(@"D:\MP3\gg.mp3", reader.WaveFormat, 128))
                 {
                     reader.CopyTo(write);
                     write.Flush();
                 }
                 reader.Flush();
             }
         }
         catch (Exception ev)
         {
             MessageBox.Show(ev.Message);
         }
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Release resources, close saved files.
        /// </summary>
        public void Close()
        {
            if (_audioWriter != null)
            {
                _audioWriter.Dispose();
                _audioWriter.Close();
            }
            else if (_lameWriter != null)
            {
                _lameWriter.Flush();
                _lameWriter.Dispose();
                _lameWriter.Close();
            }


            _isSaving     = false;
            _flushCounter = 0;

            for (short i = (short)(_openFile.getNumberOfChannels() - 1); i >= 0; i--)
            {
                _samplesBuffer.RemoveAt(i);
            }

            for (short i = 0; i < _openFile.getNumberOfChannels(); i++)
            {
                _samplesBuffer.Add(new List <byte>());
            }


            MessageBox.Show("An audio file has been saved successfully!", "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Exemplo n.º 6
0
        private void cicleRecording()  // record cicle function
        {
            this.waveSource.StopRecording();
            lameWriter.Flush();
            this.waveSource.Dispose();
            lameWriter.Dispose();

            this.fastCheck();

            this.dateStart = DateTime.Now;

            if (this.dateStart > this.dateEnd)
            {
                this.terminte("completion of the application: The current day is over.");
            }

            this.waveSource                   = new WaveInEvent();
            this.waveSource.WaveFormat        = new WaveFormat(44100, 1); //hz,kbps,chanels of record
            this.waveSource.DataAvailable    += waveIn_DataAvailable;
            this.waveSource.RecordingStopped += waveIn_RecordingStopped;

            this.dirInfo = new DirectoryInfo(this.tempDrive.Name[0] + @":\VoiceTracker\" + dateStart.ToShortDateString());
            if (!this.dirInfo.Exists)
            {
                this.dirInfo.Create();
            }
            this.tempFile = (this.tempDrive.Name[0] + @":\VoiceTracker\" + dateStart.ToShortDateString() + @"\" + dateStart.ToShortDateString() + "-" + dateStart.ToString("HH.mm.ss") + @".mp3");

            lameWriter = new LameMP3FileWriter(this.tempFile, this.waveSource.WaveFormat, 128);
            this.waveSource.StartRecording();
        }
Exemplo n.º 7
0
 void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
 {
     // flush output to finish MP3 file correctly
     wri.Flush();
     wri.Dispose();
     IsRecording = false;
 }
Exemplo n.º 8
0
 private byte[] GenerateMp3(Song song)
 {
     if (song.Notes == null)
     {
         return(null);
     }
     using (var generatedSongStream = new MemoryStream())
     {
         var mp3File  = new MemoryStream();
         var waveFile = new WaveFile(22050, BitDepth.Bit16, 1, generatedSongStream);
         var sg       = new SoundGenerator(waveFile);
         foreach (var note in song.Notes)
         {
             sg.AddSimpleTone(note.Frequency, note.Duration);
         }
         sg.Save();
         generatedSongStream.Position = 0;
         var r  = new WaveFileReader(generatedSongStream);
         var wr = new LameMP3FileWriter(mp3File, r.WaveFormat, 96);
         r.CopyTo(wr);
         wr.Flush();
         var fileData = mp3File.ToArray();
         mp3File.Dispose();
         r.Dispose();
         wr.Dispose();
         return(fileData);
     }
 }
Exemplo n.º 9
0
        public static Stream Convert(Stream inputStream)
        {
            using (var fileReader = new WaveFileReader(inputStream))
            {
                Pcm8BitToSampleProvider sampleProvider = new Pcm8BitToSampleProvider(fileReader);
                SampleToWaveProvider    waveProvider   = new SampleToWaveProvider(sampleProvider);
                var outStream = new MemoryStream();
                using (var fileWriter = new LameMP3FileWriter(outStream, waveProvider.WaveFormat, 24))
                {
                    int buff_length = 1024 * 1024;
                    var buff        = new byte[buff_length];
                    int position    = 0;
                    int length      = waveProvider.Read(buff, position, buff_length);

                    while (length > 0)
                    {
                        position += length;

                        fileWriter.Write(buff, (int)fileWriter.Position, length);
                        length = waveProvider.Read(buff, position, buff_length);
                    }
                    fileWriter.Flush();

                    return(outStream);
                }
            }
        }
Exemplo n.º 10
0
 void waveIn_RecordingStopped(object sender, StoppedEventArgs e)
 {
     // flush output to finish MP3 file correctly
     wri.Flush();
     // Dispose of objects
     waveIn.Dispose();
     wri.Dispose();
     // signal that recording has finished
     stopped = true;
 }
Exemplo n.º 11
0
 public byte[] ConvertWavToMp3(byte[] wavFile)
 {
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                 {
                     rdr.CopyTo(wtr);
                     wtr.Flush();
                     return(retMs.ToArray());
                 }
 }
Exemplo n.º 12
0
            private void streamSound()
            {
                stream = clientSocket.GetStream();
                try
                {
                    int i = 0;
                    // if the length of the bytes read is greater than zero, continue for loop
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // create a new waveIn object of type WasapiLoopbackCapture()
                        IWaveIn waveIn = new WasapiLoopbackCapture();
                        // set waveIn.DataAvailable event to waveIn_DataAvailable() defined later
                        waveIn.DataAvailable += waveIn_DataAvailable;
                        // set waveIn.RecordingStopped event to waveIn_RecordingStopped() defined later
                        waveIn.RecordingStopped += waveIn_RecordingStopped;
                        memStream = new MemoryStream();
                        // set memoryStream as the location to store the captured audio
                        wri = new LameMP3FileWriter(memStream, waveIn.WaveFormat, send_sound_quality);
                        // Start recording
                        waveIn.StartRecording();
                        // sleep for 900 * 2 milliseconds
                        Thread.Sleep(900);

                        Thread.Sleep(900);
                        // stop recording
                        waveIn.StopRecording();
                        // flush the buffer contents to memStream
                        wri.Flush();
                        //Convert memStream to array and store it onto SoundBytes byte[]
                        SoundBytes = memStream.ToArray();
                        // write the byte[] to network stream
                        stream.Write(SoundBytes, 0, SoundBytes.Length);
                        // flush the stream
                        stream.Flush();
                        wri.Dispose();
                        waveIn.Dispose();
                        Array.Clear(SoundBytes, 0, SoundBytes.Length);
                    }
                    if (Thread.CurrentThread.IsAlive)
                    {
                        Thread.CurrentThread.Abort();
                    }
                }
                catch (NullReferenceException exp)
                {
                    Debug.Write(exp.Message);
                }
                catch (Exception exp1)
                {
                    Debug.Write(exp1.Message);
                }
            }
Exemplo n.º 13
0
        /// <summary>
        /// Concat a list of WAV in a MP3 file
        /// </summary>
        /// <param name="inputFiles">List of input WAV files paths</param>
        /// <param name="outputFile">Output MP3 file path</param>
        /// <param name="id3Tag">MP3 tags</param>
        public static void WavToMp3(List <string> inputFiles, string outputFile, ID3TagData id3Tag)
        {
            var writer = new LameMP3FileWriter(outputFile, TempWaveFormat, ExportQuality, id3Tag);

            foreach (var inputFile in inputFiles)
            {
                var reader = new WaveFileReader(inputFile);
                reader.CopyTo(writer);
                reader.Close();
            }
            writer.Flush();
            writer.Close();
        }
Exemplo n.º 14
0
        public static void ConvertWaveStreamToMp3File(byte[] waveStreamAsBytes, string outputFileLocation)
        {
            using (var retMs = new MemoryStream())
                using (var ms = new MemoryStream(waveStreamAsBytes))
                    using (var rdr = new WaveFileReader(ms))
                        using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                        {
                            rdr.CopyTo(wtr);
                            wtr.Flush();
                            var byteArray = retMs.ToArray();

                            File.WriteAllBytes(outputFileLocation, byteArray);
                        }
        }
Exemplo n.º 15
0
 private void ConvertToMP3(string fileName)
 {
     byte[] wavFile = File.ReadAllBytes(fileName);
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new NA.WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                 {
                     rdr.CopyTo(wtr);
                     wtr.Flush();
                     File.WriteAllBytes(_outputMp3Name, retMs.ToArray());
                 }
     Thread.Sleep(10000);
 }
Exemplo n.º 16
0
        private void Cleanup()
        {
            _mp3Writer?.Flush();

            _waveSource?.Dispose();
            _waveSource = null;

            _silenceWaveOut?.Dispose();
            _silenceWaveOut = null;

            _mp3Writer?.Dispose();
            _mp3Writer = null;

            _tempRecordingFilePath = null;
        }
Exemplo n.º 17
0
        public void Test_Issue42()
        {
            var waveFormat = new WaveFormat();
            var tag        = new ID3TagData {
                Album = "Album"
            };

            using (var ms = new MemoryStream())
                using (var writer = new LameMP3FileWriter(ms, waveFormat, LAMEPreset.STANDARD, tag))
                {
                    byte[] empty = new byte[8192];
                    writer.Write(empty, 0, 8192);
                    writer.Flush();
                }
        }
Exemplo n.º 18
0
        // Create an in-memory MP3 file with the supplied ID3v2 tag, then read the tag back from the MP3 file
        private static ID3TagData GetTagAsWritten(ID3TagData tag)
        {
            var waveFormat = new WaveFormat();

            using (var ms = new MemoryStream())
            {
                using (var writer = new LameMP3FileWriter(ms, waveFormat, LAMEPreset.STANDARD, tag))
                {
                    byte[] empty = new byte[8192];
                    writer.Write(empty, 0, 8192);
                    writer.Flush();
                }
                ms.Position = 0;
                return(ID3Decoder.Decode(ReadID3v2Tag(ms)));
            }
        }
Exemplo n.º 19
0
        private static void ConvertBytesToMp3_Windows(byte[] wavBytes, string destinationFilePath)
        {
            // Larry Hayashi's recommended lame settings
            // "lame.exe" -V 8 -b 16 -F -B -a -m m -q 1
            // -a (downmix) not supported by NAudio.Lame yet
            // -b 16 (minimum bitrate) not supported by NAudio.Lame yet
            // -q 1 (algorithm quality) not supported by NAudio.Lame yet
            // -B (maximum bitrate) not supported by NAudio.Lame and should have an arg
            // -F (strictly enforce minimum bitrate) not supported by NAudio.Lame
            var lameConfig = new LameConfig
            {
                Preset = LAMEPreset.V8,               // -V 8
                Mode   = MPEGMode.Mono,               // -m m
                //MinimumBitRate = 16,
                //MaximumBitRate = 128,
                //ForceMinimum = true,
                //VBRAlgorithmQuality = 1
            };

            try
            {
                using (var outputStream = new MemoryStream())
                    using (var inputStream = new MemoryStream(wavBytes))
                        using (var fileReader = new WaveFileReader(inputStream))
                            using (var fileWriter = new LameMP3FileWriter(outputStream, fileReader.WaveFormat, lameConfig))
                            {
                                fileWriter.OnProgress += (writer, bytes, outputBytes, finished) =>
                                {
                                    if (finished)
                                    {
                                        var mp3Bytes = outputStream.ToArray();
                                        SaveBytes(destinationFilePath, mp3Bytes);
                                    }
                                };
                                fileReader.CopyTo(fileWriter);
                                fileWriter.Flush();
                            }
            }
            catch (ArgumentException e)
            {
                MessageBoxUtils.Show(null, string.Format(FwUtilsStrings.ConvertBytesToMp3_BadWavFile,
                                                         Path.GetFileName(destinationFilePath),
                                                         Environment.NewLine,
                                                         e.Message), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 20
0
        public void AudioStream(NetworkStream stream)
        {
            try
            {
                string response = "HTTP/1.0 200 OK\r\n"
                                  + "Content-Type: audio/mpeg\r\n"
                                  + "Connection: close\r\n"
                                  + "\n";
                byte[] bytesResponse = Encoding.ASCII.GetBytes(response);
                stream.Write(bytesResponse, 0, bytesResponse.Length);


                // Start recording from loopback
                IWaveIn waveIn = new WasapiLoopbackCapture();
                waveIn.DataAvailable    += waveIn_DataAvailable;
                waveIn.RecordingStopped += waveIn_RecordingStopped;
                // Setup MP3 writer to output at 192kbit/sec (~1 minutes per MB)
                string mp3 = "test";
                wri = new LameMP3FileWriter(@"C:\test\test_output.mp3", waveIn.WaveFormat, 192);
                waveIn.StartRecording();

                byte[] sample = new byte[9999];
                // wri.Write(sample, 0, sample.Length);
                // stream.Write(sample, 0, sample.Length);

                // System.Threading.Thread.Sleep(40000);


                System.Threading.Thread.Sleep(4050);
                waveIn.StopRecording();
                // flush output to finish MP3 file correctly
                wri.Flush();
                // Dispose of objects
                waveIn.Dispose();
                wri.Dispose();
            }
            catch
            {
            }
            finally
            {
                stream.Close();
            }
        }
Exemplo n.º 21
0
 private void stop_rec_Click(object sender, EventArgs e)
 {
     start_rec.Enabled     = true;
     stop_rec.Enabled      = false;
     groupBox1.Enabled     = true;
     browse_btn.Enabled    = true;
     label2.Visible        = false;
     path_text_box.Enabled = true;
     label2.Text           = "Click on 'Start Recording' to begin recording!";
     waveIn_rec.StopRecording();
     // stop timer and reset time_counter
     timer1.Stop();
     timer_label.Text = Convert.ToString("Total recording time: " + time_counter / 10);
     time_counter     = 0;
     // flush output to finish MP3 file correctly
     wri_rec.Flush();
     // Dispose of objects
     waveIn_rec.Dispose();
     wri_rec.Dispose();
 }
Exemplo n.º 22
0
 public string ConvertWavToMp3(string wavFilePath, string mp3FilePath, int bitRate)
 {
     try
     {
         byte[] wavFile = File.ReadAllBytes(wavFilePath);
         using (var retMs = new MemoryStream())
             using (var ms = new MemoryStream(wavFile))
                 using (var rdr = new WaveFileReader(ms))
                     using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, bitRate))
                     {
                         rdr.CopyTo(wtr);
                         wtr.Flush();
                         File.WriteAllBytes(mp3FilePath, retMs.ToArray());
                     }
     }
     catch (Exception ex)
     {
         Console.WriteLine("ConvertWavToMp3", ex);
     }
     return(mp3FilePath);
 }
Exemplo n.º 23
0
        public void startRecord()
        {
            // 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:\test\test_output.mp3", waveIn.WaveFormat, 192);
            waveIn.StartRecording();

            stopped = false;


            System.Threading.Thread.Sleep(4050);
            waveIn.StopRecording();
            // flush output to finish MP3 file correctly
            wri.Flush();
            // Dispose of objects
            waveIn.Dispose();
            wri.Dispose();
        }
Exemplo n.º 24
0
        public void Record()
        {
            //Begin No-GC
            GC.KeepAlive(Writer);
            GC.KeepAlive(waveIn);

            FireUpTheLocalAPI();

            SpotifyAPI.Pause();

            //Time to sleep to prevent lower-level crashes dependent to LAME Library
            Thread.Sleep(5000);

            //Reset The Track Playing Position
            SpotifyAPI.Skip();
            Thread.Sleep(250); //Wait 250ms to prevent Spotify Player from losing its shit
            SpotifyAPI.Previous();
            SpotifyAPI.Pause();

            RecordingCompleted = false;
            Busy = true;
            FetchTrackInfo();
            string TempTrackName = TrackName;
            string TempArtist    = Artist;
            string TempAlbum     = Album;
            Bitmap TempArtwork   = Artwork;

            Busy = false;

            waveIn = new WasapiLoopbackCapture();
            waveIn.DataAvailable    += waveIn_DataAvailable;
            waveIn.RecordingStopped += waveIn_RecordingStopped;

            SpotifyAPI.ListenForEvents = true;


            //READY?
            while (SpotifyAPI.GetStatus().Playing == false)
            {
                SpotifyAPI.Play();
                if (SpotifyAPI.GetStatus().Playing == false)
                {
                    Thread.Sleep(100);
                }
            }

            //AIM
            FetchNameFromTitle();
            while (SongNameFromWindowTitle == "Spotify")
            {
            }
            string TempName = SongNameFromWindowTitle;

            //Remove Illegal Characters From Path
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex  r           = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            string Filename    = ExportFolder + @"\" + r.Replace(TempName, "") + ".mp3";

            Writer = new LameMP3FileWriter(Filename, waveIn.WaveFormat, LAMEPreset.INSANE, null);


            //SHOOT!
            waveIn.StartRecording();


            while (TempName == SongNameFromWindowTitle)
            {
                FetchNameFromTitle();
            }

            //Skip And Previous For Setting The Track's Time Position To 0 And Pause The Song Until It Exits
            SpotifyAPI.Skip();
            SpotifyAPI.Previous();
            SpotifyAPI.Pause();

            //Flush, Write And Exit
            waveIn.StopRecording();
            Thread.Sleep(750);

            Writer.Flush();
            waveIn.Dispose();
            Writer.Dispose();

            //Tag With Correct Info
            lock (TempArtwork)
                TagTheMP3(Filename, TempTrackName, TempArtist, TempAlbum, (Bitmap)TempArtwork.Clone());

            //Pull Da Trigga
            RecordingCompleted = true;


            //Finally Kill The Thread
            MainThread.Abort();
        }
Exemplo n.º 25
0
        public static int Main(string[] args)
        {
            try
            {
                Stream sysin = new MemoryStream();
                Console.OpenStandardInput().CopyTo(sysin);

                Console.Error.WriteLine($"Copied STDIN, length {sysin.Length}");

                string id3Title     = Environment.GetEnvironmentVariable("FFM_ID3_TITLE");
                string id3Author    = Environment.GetEnvironmentVariable("FFM_ID3_AUTHOR");
                string mimeHint     = Environment.GetEnvironmentVariable("FFM_MIME");
                int?   limitSeconds = Environment.GetEnvironmentVariable("FFM_MAX_SECONDS") == null ?
                                      new int?() :
                                      Convert.ToInt32(Environment.GetEnvironmentVariable("FFM_MAX_SECONDS"));

                string typeString = InferInformationString(sysin, mimeHint);
                Console.Error.WriteLine($"TypeString is {typeString}");

                AudioFormat audioFormat = AudioFormatFromString(typeString);
                Console.Error.WriteLine($"AudioFormat is {audioFormat}");

                sysin.Position = 0;
                WaveStream readerStream = ReaderForAudioFormat(sysin, audioFormat, limitSeconds, out int seconds);
                Console.Error.WriteLine($"ReaderStream is {readerStream}");

                Stream sysout = Console.OpenStandardOutput();

                var fileWriter = new LameMP3FileWriter
                                 (
                    sysout,
                    readerStream.WaveFormat,
                    320,
                    new ID3TagData
                {
                    Title  = id3Title,
                    Artist = id3Author,
                }
                                 );

                Console.Error.WriteLine($"Setting Debug,Error,Message functions on fileWriter");

                fileWriter.SetDebugFunction(txt => Console.Error.WriteLine(txt));
                fileWriter.SetErrorFunction(txt => Console.Error.WriteLine(txt));
                fileWriter.SetMessageFunction(txt => Console.Error.WriteLine(txt));

                Console.Error.WriteLine($"Streaming operations now!");

                readerStream.CopyTo(fileWriter);
                fileWriter.Flush();
                fileWriter.Close();

                sysout.Close();

                return(seconds);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
                Console.Error.Flush();
                return(-1);
            }
        }