Ejemplo n.º 1
0
        private void recordDevice_RecordingStopped(object sender, StoppedEventArgs e)
        {
            try
            {
                Logger.WriteDebug(MethodBase.GetCurrentMethod(), "recordDevice -> Stopped");

                if (_einsatz != null)
                {
                    //Raise Event
                    EinsatzFinished.RaiseEvent(this, new EinsatzFinishedEventArgs(_einsatz));
                    //Reset Einsatz
                    _einsatz = null;
                    Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Reset einsatz -> finish");
                }

                _recordMp3Writer?.Dispose();
                _recordWaveStream?.Dispose();
            }
            catch (Exception ex)
            {
                ExceptionOccured.RaiseEvent(this, new ExceptionEventArgs
                {
                    Methode = MethodBase.GetCurrentMethod(),
                    Error   = ex
                });
            }
            finally
            {
                _recordState      = RecordState.Stopped;
                _recordWaveStream = null;
                _recordMp3Writer  = null;
            }
        }
Ejemplo n.º 2
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);
                }
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            outputFilename = String.Format("CaptingAudio_{0:yyy-MM-dd HH-mm-ss}.mp3", DateTime.Now);
            string outputFolder;

            Console.WriteLine("This program is record in computer. Same loopback record. ");
            Console.WriteLine("Save : " + Path.GetTempPath() + "\\CaptingAudio");
            Console.WriteLine("0: StartRecording, 1: StopRecord");
            outputFolder = Path.Combine(Path.GetTempPath(), "CaptingAudio");
            Directory.CreateDirectory(outputFolder);
            if (int.Parse(Console.ReadLine()) == 0)
            {
                if (waveIn == null)
                {
                    waveIn = new WasapiLoopbackCapture();
                    writer = new LameMP3FileWriter(Path.Combine(outputFolder, outputFilename), waveIn.WaveFormat, 128);

                    waveIn.DataAvailable    += OnDataAvailable;
                    waveIn.RecordingStopped += OnRecordingStopped;
                    waveIn.StartRecording();
                }
            }
            if (int.Parse(Console.ReadLine()) == 1)
            {
                StopRecording();
            }
        }
Ejemplo n.º 4
0
        public void TC02_Formats()
        {
            bool TestFormat(WaveFormat format)
            {
                using (var mp3data = new MemoryStream())
                {
                    using (var writer = new LameMP3FileWriter(mp3data, format, LAMEPreset.STANDARD))
                    {
                        var bfr = new byte[format.AverageBytesPerSecond];
                        writer.Write(bfr, 0, bfr.Length);
                    }

                    mp3data.Position = 0;
                    using (var reader = new Mp3FileReader(mp3data))
                    {
                        var encodedFormat = format;
                        return
                            ((encodedFormat.SampleRate == format.SampleRate) &&
                             (encodedFormat.Channels == format.Channels));
                    }
                }
            }

            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(44100, 1)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(22050, 2)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(22050, 1)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(16000, 2)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(16000, 1)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(11028, 2)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(11025, 1)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(8000, 2)));
            Assert.IsTrue(TestFormat(WaveFormat.CreateIeeeFloatWaveFormat(8000, 1)));
        }
Ejemplo n.º 5
0
        private void recording()  //record function
        {
            if (System.Convert.ToInt32(dateStart.ToString("mm")) <= 30)
            {
                this.delay = (29 - System.Convert.ToInt32(this.dateStart.ToString("mm"))) * 60 + (60 - System.Convert.ToInt32(this.dateStart.ToString("ss")));
            }
            else
            {
                this.delay = (59 - System.Convert.ToInt32(this.dateStart.ToString("mm"))) * 60 + (60 - System.Convert.ToInt32(this.dateStart.ToString("ss")));
            }

            this.message += "initial: voicemail recording started...\r\n";

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

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

            this.tempFile = (this.tempDrive.Name[0] + @":\VoiceTracker\" + this.dateStart.ToShortDateString() + @"\" + this.dateStart.ToShortDateString() + "-" + this.dateStart.ToString("HH.mm.ss") + @".mp3");
            lameWriter    = new LameMP3FileWriter(this.tempFile, this.waveSource.WaveFormat, 128);

            this.waveSource.StartRecording();
            stopped    = false;
            this.timer = new Timer(_ => cicleRecording(), null, this.delay * 1000, 1800 * 1000); // this.delay, 1800 <- interval ms
        }
        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();
        }
Ejemplo n.º 7
0
        public static Stream ConvertWavToMp3(Stream wavStream)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new WaveFileReader(wavStream))
            {
                if (rdr.WaveFormat.BitsPerSample == 24)                                                           //Can't go from 24 bits wav to mp3 directly, create temporary 16 bit wav
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else if (!SupportedMPEGSampleRates.Contains(rdr.WaveFormat.SampleRate))                           //Can't go from unsupported Sample Rate wav to mp3 directly
                {
                    var resampler = new WdlResamplingSampleProvider(rdr.ToSampleProvider(), SampleRate);          //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
Ejemplo n.º 8
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();
                }
        }
Ejemplo n.º 9
0
        public static void Concatenate(string outfile, params string[] mp3filenames)
        {
            if (File.Exists(outfile))
            {
                File.Delete(outfile);
            }

            LameMP3FileWriter writer = null;

            foreach (string filename in mp3filenames)
            {
                using (var reader = new Mp3FileReader(filename))
                {
                    //Console.WriteLine("doing ");

                    if (writer == null)
                    {
                        writer = new LameMP3FileWriter(outfile, reader.WaveFormat, LAMEPreset.ABR_320);
                    }
                    reader.CopyTo(writer);
                    //Console.WriteLine("something ");
                }
            }

            if (writer != null)
            {
                writer.Dispose();
            }
        }
Ejemplo n.º 10
0
        public void convert(string filepath)
        {
            Mime   mime     = new Mime();
            string mimeType = mime.Lookup(filepath);

            string mp3path = filepath.Replace(".wav", ".mp3");

            Debug.WriteLine(mp3path);

            try {
                byte[] wavFile = File.ReadAllBytes(filepath);

                using (MemoryStream memoryStream = new MemoryStream())
                    using (MemoryStream WaveMemoryStream = new MemoryStream(wavFile))
                        using (WaveFileReader WaveFileReader = new WaveFileReader(WaveMemoryStream))
                            using (LameMP3FileWriter mp3Writer = new LameMP3FileWriter(memoryStream, WaveFileReader.WaveFormat, 128)) {
                                WaveFileReader.CopyTo(mp3Writer);
                                try {
                                    File.WriteAllBytes(mp3path, memoryStream.ToArray());
                                } catch (Exception e) {
                                    // error writing file
                                    Debug.WriteLine(e);
                                }
                            }
            } catch (Exception e) {
                Debug.WriteLine(e);
            }
        }
Ejemplo n.º 11
0
        public async Task Write(Stream fileStream)
        {
            string wavIntermediate = Path.Combine(outputDirectoryProvider.GetOutputDirectory(), Guid.NewGuid() + ".wav");

            try
            {
                {
                    await waveStream.Write(wavIntermediate);

                    await progressReporter.ReportProgress(0.97, JobProgressStatus.InProgress, "Converting WAV to MP3");

                    await using var audioFileReader = new AudioFileReader(wavIntermediate);
                    await using var writer          = new LameMP3FileWriter(fileStream, audioFileReader.WaveFormat, LAMEPreset.ABR_320);
                    await audioFileReader.CopyToAsync(writer);
                } // dispose it before reporting complete
                await progressReporter.ReportProgress(1, JobProgressStatus.Complete, "File created successfully");
            }
            finally
            {
                if (File.Exists(wavIntermediate))
                {
                    try { File.Delete(wavIntermediate); } catch (Exception) { }
                }
            }
        }
 public void StopRecording()
 {
     if (waveOut != null)
     {
         waveOut.StopRecording();
         waveOut.Dispose();
         waveOut = null;
     }
     if (waveIn != null)
     {
         waveOneOut.Stop();
         waveIn.StopRecording();
         waveIn.Dispose();
     }
     if (this.waveWriter_in != null)
     {
         this.waveWriter_in.Flush();
         this.waveWriter_in.Dispose();
         this.waveWriter_in = null;
     }
     if (this.waveWriter_out != null)
     {
         this.waveWriter_out.Flush();
         this.waveWriter_out.Dispose();
         this.waveWriter_out = null;
     }
     MixFile();
     Startded = false;
 }
Ejemplo n.º 13
0
 public void Encode(WaveStream waveData, Stream outputStream)
 {
     using (LameMP3FileWriter mp3 = new LameMP3FileWriter(outputStream, waveData.WaveFormat, 128))
     {
         waveData.CopyTo(mp3);
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Create mp3 from file name
        /// </summary>
        /// <param name="fileName">The output mp3 file name</param>
        /// <param name="fileFull">Full image path</param>
        public void createMp3(string fileName, string fileFull)
        {
            model.bmpName = fileName.Replace(".bmp", "");

            using (var bmpTemp = new Bitmap(fileFull))
            {
                Bitmap bitmap = new Bitmap(bmpTemp);
                _myWavCreator.NegativeImageMode = model.negative;


                //                if (!File.Exists(OutDirectory + "\\" + fileName + ".mp3") || !File.Exists(model.realpath))

                if (!File.Exists(OutDirectory + "\\" + fileName + ".mp3"))
                {
                    MemoryStream ms = _myWavCreator.createWavMemory(bitmap, fileName, true, true);
                    ms.Position = 0;

                    using (var retMs = File.OpenWrite(OutDirectory + "\\" + fileName + ".mp3"))
                        using (var rdr = new WaveFileReader(ms))
                            using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                            {
                                rdr.CopyTo(wtr);
                            }
                }
            }
        }
Ejemplo n.º 15
0
        public void TC01_EncodeStream()
        {
            Assert.IsTrue(File.Exists(SourceFilename));

            using (var mp3data = new MemoryStream())
            {
                // Convert source wave to MP3
                using (var source = new AudioFileReader(SourceFilename))
                    using (var mp3writer = new LameMP3FileWriter(mp3data, source.WaveFormat, LAMEPreset.STANDARD))
                    {
                        TimeSpan source_time = source.TotalTime;
                        source.CopyTo(mp3writer);
                        Assert.AreEqual(source.Length, source.Position);
                    }

                // Open MP3 file and test content
                mp3data.Position = 0;
                using (var encoded = new Mp3FileReader(mp3data))
                {
                    // encoding did not supply an ID3 tag, ensure none was present in file
                    Assert.IsNull(encoded.Id3v1Tag);
                    Assert.IsNull(encoded.Id3v2Tag);

                    // the STANDARD lame preset produces a Xing header.  Check it.
                    Assert.IsNotNull(encoded.XingHeader);
                    Assert.AreEqual(mp3data.Length, encoded.XingHeader.Bytes);

                    // confirm that length is a multiple of the block size
                    int blkSize    = (encoded.XingHeader.Mp3Frame.SampleCount * encoded.WaveFormat.BitsPerSample * encoded.WaveFormat.Channels) / 8;
                    int calcLength = blkSize * encoded.XingHeader.Frames;
                    Assert.AreEqual(calcLength, encoded.Length);
                }
            }
        }
Ejemplo n.º 16
0
        private bool DownloadAndSave(string title)
        {
            try
            {
                var videoID = mDownloadList.Find(x => x.Item1 == title)?.Item2;
                if (String.IsNullOrEmpty(videoID))
                {
                    return(false);
                }

                var streamManifest = youtube.Videos.Streams.GetManifestAsync(videoID).GetAwaiter().GetResult();
                var streamInfo     = streamManifest.GetAudioOnly().FirstOrDefault();
                var kekwaitstream  = youtube.Videos.Streams.GetAsync(streamInfo).GetAwaiter().GetResult();

                var filename = string.Join("_", title.Split(Path.GetInvalidFileNameChars()));

                using (var reader = new AudioFileReader(streamInfo.Url))
                    using (var writer = new LameMP3FileWriter($"{AppDomain.CurrentDomain.BaseDirectory}Output\\{filename}.mp3", reader.WaveFormat, 128))
                        reader.CopyTo(writer);

                return(true);
            }
            catch
            {
                Thread.Sleep(300);
                return(DownloadAndSave(title));
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Starts recording
        /// </summary>
        /// <param name="recordingConfig">Recording configuration</param>
        public void Start(RecordingConfig recordingConfig)
        {
            if (_recordingStatus == RecordingStatus.NotRecording)
            {
                InitAggregator(recordingConfig.SampleRate);
                CheckRecordingDevice(recordingConfig);
                InitFader(recordingConfig.SampleRate);

                _waveSource = new WaveIn
                {
                    WaveFormat   = new WaveFormat(recordingConfig.SampleRate, recordingConfig.ChannelCount),
                    DeviceNumber = recordingConfig.RecordingDevice,
                };

                _waveSource.DataAvailable    += WaveSourceDataAvailableHandler;
                _waveSource.RecordingStopped += WaveSourceRecordingStoppedHandler;

                _mp3Writer = new LameMP3FileWriter(
                    recordingConfig.DestFilePath,
                    _waveSource.WaveFormat,
                    recordingConfig.Mp3BitRate,
                    CreateTag(recordingConfig));

                _waveSource.StartRecording();
                OnRecordingStatusChangeEvent(new RecordingStatusChangeEventArgs(RecordingStatus.Recording));
            }
        }
Ejemplo n.º 18
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);
         }
     }
 }
Ejemplo n.º 19
0
        public static Stream ConvertAiffToMp3(Stream aiffStream, string directory)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new AiffFileReader(aiffStream))
            {
                //can't go from 24 bits aif to mp3 directly, create temporary 16 bit wav
                if (rdr.WaveFormat.BitsPerSample == 24)
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
Ejemplo n.º 20
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);
        }
        /*async*/ void button3_Click(object sender, EventArgs e)
        {
            try
            {
                cap = new WasapiLoopbackCapture();
                cap.DataAvailable    += InputBufferToFileCallback;
                cap.RecordingStopped += stoppedrecordingCallback;
                var outputFilePath = "C:\\Users\\Smail\\Desktop\\output-sound-card.mp3";
                writer      = new WaveFileWriter(outputFilePath, cap.WaveFormat);
                file_base64 = new StreamWriter(@"C:\\Users\\Smail\\Desktop\\output-sound-Base64.txt");


                var outputFilePath2 = "C:\\Users\\Smail\\Desktop\\output-sound-card2.mp3";
                ms = new MemoryStream();

                wtr = new LameMP3FileWriter(ms, cap.WaveFormat, (cap.WaveFormat.BitsPerSample * cap.WaveFormat.SampleRate * cap.WaveFormat.Channels) / 1000);



                //retMs = new MemoryStream();
                //rdr = new RawSourceWaveStream(ms, cap.WaveFormat);
                //wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128);

                cap.StartRecording();
            }
            catch (Exception ex)
            {
                MessageBox.Show("error while listening :" + ex.Message);
            }
        }
Ejemplo n.º 22
0
        private static void CompressToMP3()
        {
            var bitRate = 128;

            using (var reader = new AudioFileReader(_waveFileName))
                using (var writer = new LameMP3FileWriter(_targetFileName, reader.WaveFormat, bitRate)) reader.CopyTo(writer);
        }
Ejemplo n.º 23
0
        public static void WriteSong(string waveFileName, string mp3FileName, SongInfo info)
        {
            using (AudioFileReader reader = new AudioFileReader(waveFileName)) {
                //Console.WriteLine(reader.WaveFormat.BitsPerSample);
                WaveFormat format = WaveFormat.CreateIeeeFloatWaveFormat(reader.WaveFormat.SampleRate, reader.WaveFormat.Channels);                //new WaveFormat(reader.WaveFormat.SampleRate, 16, 2)
                using (var resampler = new MediaFoundationResampler(reader, format)) {
                    // resampler.ResamplerQuality = 60;
                    WaveFileWriter.CreateWaveFile(Path.GetFileNameWithoutExtension(mp3FileName) + ".wav", resampler);
                }
            }

            using (WaveFileReader reader = new WaveFileReader(Path.GetFileNameWithoutExtension(mp3FileName) + ".wav")) {
                using (LameMP3FileWriter writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, 705)) {
                    //Console.WriteLine(reader.WaveFormat.BitsPerSample);
                    reader.CopyTo(writer);
                }
            }

            File.Delete(Path.GetFileNameWithoutExtension(mp3FileName) + ".wav");

            TagLib.File f = TagLib.File.Create(mp3FileName);
            f.Tag.Album        = info.Album;
            f.Tag.Artists      = new string[] { info.Artist };
            f.Tag.AlbumArtists = new string[] { info.Artist };
            f.Tag.Title        = info.Title;
            f.Tag.Genres       = new string[] { "Soundtrack" };
            f.Tag.Track        = (uint)info.TrackNumber;
            f.Save();
        }
Ejemplo n.º 24
0
 public override void StopRecording()
 {
     base.StopRecording();
     _captureStream.DataAvailable -= CaptureStream_DataAvailable;
     _outWriter.Dispose();
     _outWriter = null;
 }
Ejemplo n.º 25
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();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Converts the recorded WAV file to MP3. The WAV file will be converted
        /// ONLY if the recording was finished successfully (using StopRecording).
        /// </summary>
        public void ConvertToMP3()
        {
            if (!_isRecording)
            {
                // Convert WAV to MP3 using libmp3lame library
                try
                {
                    _state = RecorderState.ConvertingInProgress;
                    using (var reader = new AudioFileReader(_tempWavFilePath))
                        using (var writer = new LameMP3FileWriter(_mp3FilePath, reader.WaveFormat, _mp3Preset))
                            reader.CopyTo(writer);
                }
                catch (Exception)
                {
                    _state = RecorderState.ConvertError;

                    return;
                }
            }
            else
            {
                _state = RecorderState.ConvertError;
                return;
            }

            _state = RecorderState.ConvertingFinsihed;
        }
Ejemplo n.º 27
0
        private void button4_Click(object sender, EventArgs e)
        {
            synth.SelectVoice(ddlVoices.SelectedItem.ToString());
            if (audioFile != null)
            {
                audioFile.Close();
            }
            synth.SpeakAsyncCancelAll();
            Thread.Sleep(1000);
            Console.WriteLine("Redirecting output");
            synth.SetOutputToWaveFile("temp.wav");
            Console.WriteLine("Speaking text...");
            synth.Speak(rtfText.Text);
            Console.WriteLine("Done speaking text");
            synth.SetOutputToNull();
            Console.WriteLine("Done setting output to null");
            SaveFileDialog ofd = new SaveFileDialog();

            ofd.Filter = "Text files (*.mp3)|*.mp3|All files (*.*)|*.*";
            ofd.ShowDialog();
            using (var reader = new AudioFileReader("temp.wav"))
                using (var writer = new LameMP3FileWriter(ofd.FileName, reader.WaveFormat, LAMEPreset.ABR_128))
                    reader.CopyTo(writer);
            LastSavedFile = ofd.FileName;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Applies changes based on the state of this instance, and saves to the specified path.
        /// </summary>
        /// <param name="path">The file path.</param>
        public void Save(string path)
        {
            // applies peak normalization to the reader
            if (this.Settings.NormalizeVolume)
            {
                this.NormalizationProvider.ApplyPeakNormalization(this.Reader);
            }

            // determine the output type
            if (this.Settings.EncodeToMP3 &&
                this.Reader.Length > 0)
            {
                using (var writer = new LameMP3FileWriter(path, this.Reader.WaveFormat, MP3_BIT_RATE))
                {
                    var buffer = new byte[1024 * 4];
                    var read   = 0;

                    while ((read = this.Reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        writer.Write(buffer, 0, read);
                    }
                }
            }
            else
            {
                WaveFileWriter.CreateWaveFile(path, this.Reader);
            }
        }
Ejemplo n.º 29
0
        private static Task <byte[]> CompressWav(this byte[] wav)
        {
            var task = Task.Run(() =>
            {
                try
                {
                    using (var ms = new MemoryStream(wav))
                    {
                        using (var reader = new WaveFileReader(ms))
                        {
                            var newFormat = new WaveFormat(8000, 16, 1);

                            using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))
                            {
                                using (var outms = new MemoryStream())
                                {
                                    using (var writer = new LameMP3FileWriter(outms, conversionStream.WaveFormat, 24, null))
                                    {
                                        conversionStream.CopyTo(writer);

                                        return(outms.ToArray());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            });

            return(task);
        }
Ejemplo n.º 30
0
        private void startRecording()
        {
            try
            {
                if (_einsatz == null)
                {
                    return;
                }

                //Record Device
                _recordWaveStream = new WaveInEvent
                {
                    DeviceNumber = 0,
                    WaveFormat   = new WaveFormat(44100, 16, 2)
                };
                _recordWaveStream.DataAvailable    += recordDevice_DataAvailable;
                _recordWaveStream.RecordingStopped += recordDevice_RecordingStopped;
                _recordWaveStream.StartRecording();

                _recordMp3Writer = new LameMP3FileWriter(_einsatz.RecordPath, _recordWaveStream.WaveFormat, 32);
                _recordState     = RecordState.Recording;

                Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"recordDevice -> Started({_einsatz.RecordPath})");
            }
            catch (Exception)
            {
                ExceptionOccured.RaiseEvent(this, new ExceptionEventArgs
                {
                    Methode = MethodBase.GetCurrentMethod(),
                    Message = "recordDevice -> error on start"
                });
            }
        }