MP3 encoding class, uses libmp3lame DLL to encode.
Inheritance: Stream
Example #1
3
 public static void ConvertWavToMp3(string WavFile, string outPutFile)
 {
     CheckAddBinPath();
     WaveFileReader rdr = new WaveFileReader(WavFile);
     using (var wtr = new LameMP3FileWriter(outPutFile, rdr.WaveFormat, 128))
     {
         rdr.CopyTo(wtr);
         rdr.Dispose();
         wtr.Dispose();
         return;
     }
 }
Example #2
1
 public static byte[] ConvertWavToMp3(byte[] wavFile)
 {
     CheckAddBinPath();
     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);
         return retMs.ToArray();
     }
 }
Example #3
1
        //Dispose MP3/WAV Writer
        protected void DisposeWriter()
        {
            switch(this._RecordingFormat)
            {
                case OutputFormat.MP3:
                    if (_MP3Writer == null)
                        return;

                    _MP3Writer.Flush();
                    _MP3Writer.Dispose();
                    _MP3Writer = null;
                    break;

                case OutputFormat.WAV:
                     if (_WAVWriter == null)
                        return;

                    _WAVWriter.Flush();
                    _WAVWriter.Dispose();
                    _WAVWriter = null;
                    break;
            }
        }
Example #4
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();
            }
        }
Example #5
0
        /// <summary>
        ///  Convert WAV to MP3 using libmp3lame library
        /// </summary>
        /// <param name="waveFileName">WAV filename</param>
        /// <param name="mp3FileName">MP3 filename</param>
        /// <param name="bitRate">Bit rate, default 128</param>
        /// <param name="artist">Optional artist name</param>
        /// <param name="album">Optional album name</param>
        /// <param name="setID3Tags">Set ID3 tags</param>
        public static bool WavToMP3(string waveFileName, string mp3FileName, int bitRate = 128, string artist = null, string album = null, bool setID3Tags = false, string genre = "148")
        {
            bool result = true;
            try
            {
                ID3TagData tags = new ID3TagData();
                if (setID3Tags)
                {
                    if (!String.IsNullOrEmpty(artist))
                    {
                        tags.Artist = artist;
                        tags.Album = album;
                        tags.Genre = genre;
                    }
                }

                using (var reader = new WaveFileReader(waveFileName))
                using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate, tags))
                    reader.CopyTo(writer);

            }
            catch (Exception)
            {
                result = false;
            }

            return result;
        }
Example #6
0
        public void Start()
        {
            listener = new TcpListener(Port);
            listener.Start();

            new Thread(() =>
            {
                while (true)
                {

                    try
                    {

                        TcpClient client = listener.AcceptTcpClient();

                        var netStream = client.GetStream();

                        var mp3Stream = new NAudio.Lame.LameMP3FileWriter(netStream, WaveFormat.CreateIeeeFloatWaveFormat(44100, 2), NAudio.Lame.LAMEPreset.ABR_320);

                        clients.Add(new Tuple<TcpClient, NetworkStream, LameMP3FileWriter>(client, netStream, mp3Stream));

                    }
                    catch
                    {

                    }
                }
            }).Start();
        }
        private void StopRecord(Exception e)
        {
            lock (_lck) {
                _ripper.FrameDecompressed -= OnFrameDecompressed;
                _ripper.StreamEnded       -= (ex) => StopRecord(ex);

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

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

                State = StreamRecorderStates.Stopped;

                if (_recordingEnded != null)
                {
                    _recordingEnded(e);
                }
            }
        }
Example #8
0
        public MemoryStream GetMp3Sample(int seconds, string filepath = "")
        {
            try
            {
                var stream = new MemoryStream();
                // Start recording from loopback
                IWaveIn waveIn = new WasapiLoopbackCapture();
                waveIn.DataAvailable += waveIn_DataAvailable;
                waveIn.RecordingStopped += waveIn_RecordingStopped;
                // Setup MP3 writer to output at 96kbit/sec
                writer = new LameMP3FileWriter(stream, waveIn.WaveFormat, LAMEPreset.ABR_96);
                _isRecording = true;
                waveIn.StartRecording();

                // Wait for X seconds
                System.Threading.Thread.Sleep(seconds * 1000);
                waveIn.StopRecording();

                // flush output to finish MP3 file correctly
                writer.Flush();
                // Dispose of objects
                waveIn.Dispose();
                writer.Dispose();

                if (filepath != "")
                    using (var file = new FileStream(filepath, FileMode.Create, FileAccess.Write))
                        stream.WriteTo(file);

                return stream;
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void WriteFrame(FrameDecompressedEventArgs <Mp3Frame> e)
        {
            if (State != StreamRecorderStates.Recording)
            {
                return;
            }

            if (e.DecompressedDataLen <= 0)
            {
                return;
            }

            if (_mp3writer == null)
            {
                _mp3writer = new LameMP3FileWriter(
                    _fileStream,
                    e.DecompressedFormat,
                    e.Frame.BitRate,
                    new ID3TagData {
                    Title   = $"{e.StreamSource.DisplayName} ({DateTime.Now.ToString()})",
                    Comment = e.StreamSource.StreamUrl
                }
                    );
            }

            _mp3writer.Write(e.DecompressedData, 0, e.DecompressedDataLen);
        }
Example #10
0
        /*public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename)
         * {
         *  //rewind to beginning of stream
         *  ms.Seek(0, SeekOrigin.Begin);
         *
         *  using (var retMs = new MemoryStream())
         *  using (var rdr = new WaveFileReader(ms))
         *  using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90))
         *  {
         *      rdr.CopyTo(wtr);
         *  }*/



        public void cnv(string sourceFilename, string targetFilename)
        {
            using (var reader = new NAudio.Wave.AudioFileReader(sourceFilename))
                using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD))
                {
                    reader.CopyTo(writer);
                }
        }
 public void Init(string path)
 {
     durationStopwatch = new Stopwatch();
     waveIn = new WasapiLoopbackCapture();
     wri = new LameMP3FileWriter(@path + ".mp3", waveIn.WaveFormat, 32);
     waveOut = new WaveOut();
     waveOut.Init(new SilenceGenerator());
 }
Example #12
0
        public static void ConvertToMP3(string inFile, string outFile, int bitRate = 64)
        {

            using (var reader = new AudioFileReader(inFile))
            {
                using (var writer = new LameMP3FileWriter(outFile, reader.WaveFormat, bitRate))
                    reader.CopyTo(writer);
            }
        }
Example #13
0
 /// <summary>
 /// Converte um WaveStream para MP3Stream.
 /// </summary>
 /// <param name="wavFile"/>
 /// <returns></returns>
 public static MemoryStream ConverterWaveStreamParaMp3Stream(Wave32To16Stream wavFile)
 {
     var retMs = new MemoryStream();
     using (var wtr = new LameMP3FileWriter(retMs, wavFile.WaveFormat, 128))
     {
         wavFile.CopyTo(wtr);
         return retMs;
     }
 }
 public byte[] ConvertToMp3(string file, int bitrate = 128)
 {
     using (var retMs = new MemoryStream())
         using (var rdr = new WaveFileReader(file))
             using (var wtr = new NAudio.Lame.LameMP3FileWriter(retMs, rdr.WaveFormat, bitrate))
             {
                 rdr.CopyTo(wtr);
                 return(retMs.ToArray());
             }
 }
Example #15
0
        public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename)
        {
            //rewind to beginning of stream
            ms.Seek(0, SeekOrigin.Begin);

            using (var retMs = new MemoryStream())
            using (var rdr = new WaveFileReader(ms))
            using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90))
            {
                rdr.CopyTo(wtr);
            }
        }
Example #16
0
        public void ConvertWavToMp3(string WavFile, string outPutFile)
        {
            WaveFileReader rdr = new WaveFileReader(WavFile);

            using (var wtr = new NAudio.Lame.LameMP3FileWriter(outPutFile, rdr.WaveFormat, 128))
            {
                rdr.CopyTo(wtr);
                rdr.Dispose();
                wtr.Dispose();
                return;
            }
        }
Example #17
0
 public static void Start(TrackDto track)
 {
     lock (Lock)
     {
         currentTrack = track;
         waveIn = new WasapiLoopbackCapture();
         lameMp3FileWriter = new LameMP3FileWriter(GetFileName(), waveIn.WaveFormat, 256);
         recordingStopped = new ManualResetEvent(false);
         waveIn.DataAvailable += LoopbackDataAvailable;
         waveIn.RecordingStopped += LoopbackRecordingStopped;
         waveIn.StartRecording();
     }
 }
Example #18
0
 private static void Cleanup()
 {
     if (waveIn != null) // working around problem with double raising of RecordingStopped
     {
         waveIn.Dispose();
         waveIn = null;
     }
     if (writer != null)
     {
         writer.Close();
         writer = null;
     }
 }
        private static void WmaToMp3(XConvertJob param)
        {
            var targetFilename = string.IsNullOrEmpty(param.AlternativeOutputPath) ? param.SourceFileName.GenerateOutPutPath(XFileType.Mp3) :
                                 param.AlternativeOutputPath;

            if (param.SourceData != null)
            {
                File.WriteAllBytes(param.SourceFileName, param.SourceData);
            }
            using (var reader = new NAudio.Wave.AudioFileReader(param.SourceFileName))
                using (var writer = new NAudio.Lame.LameMP3FileWriter(targetFilename, reader.WaveFormat, NAudio.Lame.LAMEPreset.STANDARD))
                {
                    reader.CopyTo(writer);
                }
            param.ResulFileName = targetFilename;
        }
Example #20
0
        public WasapiProvider()
        {
            // Init Pipes
            this.recordingStream = new PipeStream();
            this.LoopbackMp3Stream = new PipeStream();
            this.LoopbackL16Stream = new PipeStream();

            // Init Wave Processor thread
            Thread waveProcessorThread = new Thread(new ThreadStart(this.waveProcessor)) { Priority = ThreadPriority.Highest };

            // Init Wasapi Capture
            this.loopbackWaveIn = new WasapiLoopbackCapture();
            this.loopbackWaveIn.DataAvailable += new EventHandler<WaveInEventArgs>(this.loopbackWaveIn_DataAvailable);
            
            // Init Raw Wav (16bit)
            WaveStream rawWave16b = new Wave32To16Stream(new RawSourceWaveStream(this.recordingStream, NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(this.loopbackWaveIn.WaveFormat.SampleRate, this.loopbackWaveIn.WaveFormat.Channels)));

            // Convert Raw Wav to PCM with audio format in settings
            var audioFormat = AudioSettings.GetAudioFormat();
            if (rawWave16b.WaveFormat.SampleRate == audioFormat.SampleRate
                && rawWave16b.WaveFormat.BitsPerSample == audioFormat.BitsPerSample
                && rawWave16b.WaveFormat.Channels == audioFormat.Channels)
            {
                // No conversion !
                this.rawConvertedStream = null;
                this.pcmStream = WaveFormatConversionStream.CreatePcmStream(rawWave16b);
            }
            else
            {
                // Resampler
                this.rawConvertedStream = new WaveProviderToWaveStream(new MediaFoundationResampler(rawWave16b, audioFormat));
                this.pcmStream = WaveFormatConversionStream.CreatePcmStream(rawConvertedStream);
            }

            // Init MP3 Encoder
            this.mp3Writer = new LameMP3FileWriter(this.LoopbackMp3Stream, pcmStream.WaveFormat, AudioSettings.GetMP3Bitrate());

            // Start Recording
            this.loopbackWaveIn.StartRecording();

            // Start Wave Processor thread
            waveProcessorThread.Start();
        }
Example #21
0
        // Writes wave memorystream out to a file.
        private void WriteMP3(byte[] wave, string file)
        {
            string outputFile = file;

            if (File.Exists(outputFile))
            {
                outputFile = this.GetAlternatePath(outputFile);
            }

            using (MemoryStream waveMemoryStream = new MemoryStream(wave))
            {
                using (WaveFileReader reader = new WaveFileReader(waveMemoryStream))
                {
                    using (LameMP3FileWriter writer = new LameMP3FileWriter(outputFile, reader.WaveFormat, LAMEPreset.V4))
                    {
                        reader.CopyTo(writer);
                    }
                }
            }
        }
Example #22
0
        //Constructor
        public Recorder()
        {
            this._Ready         = false;
            this._Recording     = false;
            this._Debug         = false;
            this.RecordSilence  = false;
            this.Paused         = false;

            this._Hertz     = 0; //auto
            this._BitRate   = 128;
          
            this._MP3Writer = null;
            this._WAVWriter = null;
            this._Capturer  = null;

            this._RecordingFormat = OutputFormat.WAV;

            this._DestinationFileName = String.Empty;
            this._DestinationRoot     = String.Empty;
        }
Example #23
0
        public static void ConvertWavStreamToMp3File(Configuration cfg, ref MemoryStream ms, string savetofilename)
        {
            //rewind to beginning of stream
            ms.Seek(0, SeekOrigin.Begin);

            using (var retMs = new MemoryStream())
            {
                using (var rdr = new WaveFileReader(ms))
                {
                    using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, cfg.MP3BitRate))
                    {
                        rdr.CopyTo(wtr);
                        wtr.Close();
                    }

                    rdr.Close();

                    Console.WriteLine(savetofilename + " ok.");
                }
            }
        }
Example #24
0
        private void splitMp3(string trackPath, int startPos, int endPos, MediaFoundationReader reader, ID3TagData tagData)
        {
            int progress = 0;

            using (var writer = new NAudio.Lame.LameMP3FileWriter(trackPath, reader.WaveFormat, NAudio.Lame.LAMEPreset.V3, tagData))
            {
                reader.Position = startPos;
                byte[] buffer = new byte[1024];
                while (reader.Position < endPos)
                {
                    int bytesRequired = (int)(endPos - reader.Position);
                    if (bytesRequired > 0)
                    {
                        int bytesToRead = Math.Min(bytesRequired, buffer.Length);
                        int bytesRead   = reader.Read(buffer, 0, bytesToRead);
                        if (bytesRead > 0)
                        {
                            writer.Write(buffer, 0, bytesRead);
                            progress += bytesRead;
                        }
                    }
                }
            }
        }
Example #25
0
        internal static void CreateMp3File(string filename, IWaveProvider sourceProvider, int bitRate, Action<long> progressCallback)
        {
            Debug.Assert(progressCallback != null);

            using (var writer = new LameMP3FileWriter(filename, sourceProvider.WaveFormat, bitRate))
            {
                long outputLength = 0;
                var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond * 4];
                while (true)
                {
                    int bytesRead = sourceProvider.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        // end of source provider
                        break;
                    }
                    outputLength += bytesRead;
                    // Write will throw exception if WAV file becomes too large
                    writer.Write(buffer, 0, bytesRead);

                    progressCallback(bytesRead);
                }
            }
        }
        public static byte[] ConvertAiffToMp3(byte[] aiffFile, string directory)
        {
            byte[] mp3bytes = null;
            var newFormat = new WaveFormat(bitRate, bitDepth, channels);
            try
            {
                uniqueTempFileCounter += 1;
                var tempFile = Path.Combine(directory, "tempdata"+ uniqueTempFileCounter +".wav");

                using (var ms = new MemoryStream(aiffFile))
                using (var rdr = new AiffFileReader(ms))
                {
                    if (rdr.WaveFormat.BitsPerSample == 24) //can't go from 24 bits aif 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
                            mp3bytes = ConvertWavToMp3(tempFile, true); //file to mp3 bytes
                    }
                    else
                    {
                        using (var retMs = new MemoryStream())
                        using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, bitRate))
                        {
                            rdr.CopyTo(wtr);
                            mp3bytes = retMs.ToArray();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            return mp3bytes;
        }
 public WaveToMp3Convertor(string fileName, Options options)
 {
     _stream = new FileStream(fileName + ".mp3", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
     var waveFormat = new WaveFormat((int)options.InputSamplingRate.Value, options.InputeBits, options.InputChannels.Value);
     _mp3Writer = new LameMP3FileWriter(_stream, waveFormat, options.BitRate.Value);
 }
 // Convert WAV to MP3 using libmp3lame library
 public static void WaveToMP3(string waveFileName, string mp3FileName, int bitRate = 128)
 {
     using (var reader = new WaveFileReader(waveFileName))
     using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))
         reader.CopyTo(writer);
 }
Example #29
0
        public void AudioDeviceDataAvailable(object sender, DataAvailableEventArgs e)
        {
            if (Levels == null || IsReconnect)
                return;
            try
            {
                lock (_lockobject)
                {
                    Helper.FrameAction fa;
                    if (!Recording)
                    {
                        var dt = Helper.Now.AddSeconds(0 - Micobject.settings.buffer);
                        while (Buffer.Count > 0)
                        {
                            if (Buffer.TryPeek(out fa))
                            {
                                if (fa.TimeStamp < dt)
                                {
                                    if (Buffer.TryDequeue(out fa))
                                        fa.Nullify();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    fa = new Helper.FrameAction(e.RawData, e.BytesRecorded, Levels.Max(), Helper.Now);
                    Buffer.Enqueue(fa);

                }

                if (Micobject.settings.needsupdate)
                {
                    Micobject.settings.samples = AudioSource.RecordingFormat.SampleRate;
                    Micobject.settings.channels = AudioSource.RecordingFormat.Channels;
                    Micobject.settings.needsupdate = false;
                }

                OutSockets.RemoveAll(p => p.TcpClient.Client.Connected == false);
                if (OutSockets.Count>0)
                {
                    if (_mp3Writer == null)
                    {
                        _audioStreamFormat = new WaveFormat(22050, 16, Micobject.settings.channels);
                        var wf = new WaveFormat(_audioStreamFormat.SampleRate, _audioStreamFormat.BitsPerSample, _audioStreamFormat.Channels);
                        _mp3Writer = new LameMP3FileWriter(_outStream, wf, LAMEPreset.STANDARD);
                    }

                    byte[] bSrc = e.RawData;
                    int totBytes = bSrc.Length;

                    var ws = new TalkHelperStream(bSrc, totBytes, AudioSource.RecordingFormat);
                    var helpStm = new WaveFormatConversionStream(_audioStreamFormat, ws);
                    totBytes = helpStm.Read(_bResampled, 0, 22050);

                    ws.Close();
                    ws.Dispose();
                    helpStm.Close();
                    helpStm.Dispose();

                    _mp3Writer.Write(_bResampled, 0, totBytes);

                    var bterm = Encoding.ASCII.GetBytes("\r\n");

                    if (_outStream.Length > 0)
                    {
                        var bout = new byte[(int) _outStream.Length];

                        _outStream.Seek(0, SeekOrigin.Begin);
                        _outStream.Read(bout, 0, (int) _outStream.Length);

                        _outStream.SetLength(0);
                        _outStream.Seek(0, SeekOrigin.Begin);

                        foreach (var s in OutSockets)
                        {
                            var b = Encoding.ASCII.GetBytes(bout.Length.ToString("X") + "\r\n");
                            try
                            {
                                s.Stream.Write(b, 0, b.Length);
                                s.Stream.Write(bout, 0, bout.Length);
                                s.Stream.Write(bterm, 0, bterm.Length);
                            }
                            catch
                            {
                                OutSockets.Remove(s);
                                break;
                            }
                        }
                    }

                }
                else
                {
                    if (_mp3Writer != null)
                    {
                        _mp3Writer.Close();
                        _mp3Writer = null;
                    }
                }

                if (DataAvailable != null)
                {
                    DataAvailable(this, new NewDataAvailableArgs((byte[])e.RawData.Clone()));
                }

                if (_reconnectTime != DateTime.MinValue)
                {
                    Micobject.settings.active = true;
                    _errorTime = _reconnectTime = DateTime.MinValue;
                    DoAlert("reconnect");
                }
                _errorTime = DateTime.MinValue;

            }
            catch (Exception ex)
            {
                if (ErrorHandler != null)
                    ErrorHandler(ex.Message);
            }
        }
Example #30
0
 private void Wavein_DataAvailable(object sender, WaveInEventArgs e)
 {
     float level = this.GetCurrentPeak();
     if (level > voiceLevel)
     {
         if (writer != null)
         {
             writer.Write(e.Buffer, 0, e.BytesRecorded);
         }
         else
         {
             currentFileName = GetNextFileName();
             writer = new LameMP3FileWriter(currentFileName, wavein.WaveFormat, LAMEPreset.MEDIUM_FAST);
         }
     }
 }
        private void FlushBufferToFile()
        {
            IsRecording = false;
            this.OnAudioData(new AudioDataEventArgs());

            _prerecord.Clear();
            _recordingEnd = DateTime.Now;

            var dirName = Options.GetActualOutputDir();

            if (Options.CreateDateSubdirectories)
            {
                dirName = Path.Combine(dirName, _recordingEnd.Date.ToString("dd-MM-yy"));
            }

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            var fileName = "Record from " + _recordingBegin.ToString("dd-MM-yy HH:mm:ss")
                           + " to " + _recordingEnd.ToString("dd-MM-yy HH:mm:ss");

            fileName += ".mp3";

            fileName = NormalizeFileName(fileName);

            fileName = Path.Combine(dirName, fileName);

            if (_recordingBegin != DateTime.MinValue)
            {
                var audioLengthMs = _recordingEnd.Subtract(_recordingBegin).TotalMilliseconds;

                // 27/01/16 don`t save empty audio (started by random sygnal pick)
                if (Math.Abs(audioLengthMs - Options.StopIntegrationTime - Options.PrerecordDuration) > Options.MinAudioLength)
                {
                    try
                    {
                        //var phoneNumber = new Aon().RecognizePhoneNumber(Options.MicrophoneBitRate,
                        //    _recordingBufferStream.ToArray());

                        //if (!string.IsNullOrEmpty(phoneNumber))
                        //{
                        //    var fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

                        //    fileNameNoExt = fileNameNoExt + "_" + phoneNumber;

                        //    var fileExt = Path.GetExtension(fileName);

                        //    fileName = NormalizeFileName(Path.Combine(Path.GetDirectoryName(fileName),
                        //        fileNameNoExt + fileExt));
                        //}

                        _recordingBufferStream.Seek(0, SeekOrigin.Begin);
                        using (var mp3File = new LameMP3FileWriter(fileName,
                            _waveIn.WaveFormat, Options.OutputBitRate))
                        {
                            _recordingBufferStream.CopyTo(mp3File);
                            mp3File.Flush();
                        }

                        OnAfterFlushToFile(new FileSystemEventArgs(WatcherChangeTypes.Created, dirName, fileName));

                        if (!string.IsNullOrEmpty(Options.AfterMp3FlushCommand))
                        {
                            var cmd = Options.AfterMp3FlushCommand;
                            try
                            {
                                var psi = new ProcessStartInfo(cmd, $@"""{fileName}""");
                                psi.WindowStyle = ProcessWindowStyle.Hidden;
                                Process.Start(psi);
                            }
                            catch (Exception e)
                            {
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                }
            }

            _recordingBufferStream = new MemoryStream();
            _recordingBegin = DateTime.MinValue;
            _recordingEnd = DateTime.MinValue;
        }
        public void ParseText(string text)
        {
            inputText = text.ToLower(new CultureInfo("en-US", false));
            inputText = TextReplace(inputText);
            //this.inputText = inputText.Replace("\n", "/");
            inputText = inputText.Replace("“", "\"");
            inputText = inputText.Replace("”", "\"");
            string[] lines = Regex.Split(inputText, "\n");

            List<string> sentences = new List<string>();
            List<string> symbols = new List<string>();
            List<bool> quotes = new List<bool>();
            


            foreach (string line in lines)
            {

                if (line.Length == 1 && line.GetHashCode() == -842352733)
                    continue;
                else if (line.Length == 0)
                    continue;

                DeleteOperation operation = DeleteOperation.None;
                foreach (KeyValuePair<string, DeleteOperation> kvp in deleteDictionary)
                {
                    if (line.Contains(kvp.Key))
                    {
                        operation = kvp.Value;
                        break;
                    }
                }

                if (operation == DeleteOperation.DeleteAllAfter)
                    break;
                else if (operation == DeleteOperation.DeleteLine)
                    continue;


                string[] quoteSplit = Regex.Split(line, "\"");

                for (int q = 0; q < quoteSplit.Length; q++)
                {
                    bool quoted = q % 2 == 1 ? true : false;
                    string[] parts = Regex.Split(quoteSplit[q], "([,…。:?!])");

                    string sentence = "";
                    string symbol = "";
                    
                    //Console.WriteLine("======" + parts.Length);
                    for (int i = 0; i < parts.Length; i++)
                    {
                        if (parts[i].Length == 0)
                            continue;
                        sentence = parts[i];

                        while (i + 1 < parts.Length)
                        {
                            //Console.WriteLine("Symbol " + parts[i + 1] + " " + parts[i + 1].GetHashCode());
                            if (parts[i + 1].GetHashCode() == 757602046)
                            {
                                i++;
                                continue;
                            }
                            if (",…。:?!".Contains(parts[i + 1]))
                            {
                                symbol += parts[i + 1];
                                i++;
                                continue;
                            }
                            break;
                        }
                        if (symbol.Length == 0)
                            symbol = "。";

                        //BuildPrompt(sentence, symbol, quoted);
                        sentences.Add(sentence);
                        symbols.Add(symbol);
                        quotes.Add(quoted);
                        sentence = "";
                        symbol = "";
                    }

                }
            }

            for (int i = 0; i < sentences.Count; i++)
            {
                BuildPrompt(sentences[i], symbols[i], quotes[i]);
                int percent = (int)(100.0f * (float)(i + 1) / (float)sentences.Count);
                //Console.Write("\r " + fileName + " Progress: {0}%   ", percent);
                Console.WriteLine(percent);
            }

            if (outputFileLocation != null)
            {
                ms.Seek(0, SeekOrigin.Begin);

                //Convert from wav to mp3 to save space
                using (var rdr = new WaveFileReader(ms))
                using (var wtr = new LameMP3FileWriter(outputFileLocation, rdr.WaveFormat, LAMEPreset.VBR_90))
                {
                    rdr.CopyTo(wtr);
                }
            }

        }
Example #33
0
        private static void GenerateMp3File(string filename = "output")
        {

            using (var reader = new WaveFileReader(GenerateMemoryStream()))
            using (var writer = new LameMP3FileWriter(filename + ".mp3", reader.WaveFormat, LAMEPreset.ABR_32))
                reader.CopyTo(writer);
        }
        public override void DownloadAndPlayItem(PhraseItem item, string folder)
        {
            String SSMLText = String.Format(@"<?xml version=""1.0""?>
            <speak xmlns=""http://www.w3.org/2001/10/synthesis"" version=""1.0"" xml:lang=""{1}"">
            <p>
            <s>{0}</s>
            </p>
            </speak>
            ", item.Phrase.Replace("&", "&amp;"), SelectedVoice.Language);

            try
            {
                new Task(() =>
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        using (var synth = new SpeechSynthesizer())
                        {
                            synth.SelectVoice(SelectedVoice.Name);
                            synth.Volume = Int32.Parse(SelectedDiscreteVolume);
                            synth.Rate = Int32.Parse(SelectedDiscreteSpeed);
                            synth.SetOutputToWaveStream(ms);//.SetOutputToWaveFile(String.Format("{0}\\wav22050\\{1}\\{2}.wav", folder, item.Folder, item.FileName));
                            synth.SpeakSsml(SSMLText);
                        }
                        ms.Seek(0, SeekOrigin.Begin);
                        using (WaveFileReader wav = new WaveFileReader(ms))// String.Format("{0}\\wav22050\\{1}\\{2}.wav", folder, item.Folder, item.FileName)))
                        {
                            using (FileStream fs = new FileStream(String.Format("{0}\\mp3\\{1}\\{2}.mp3", folder, item.Folder, item.FileName), FileMode.Create))
                            {
                                using (var writer = new LameMP3FileWriter(fs, wav.WaveFormat, 128))
                                {
                                    wav.CopyTo(writer);
                                }
                            }
                        }
                        ms.Seek(0, SeekOrigin.Begin);
                        using (WaveFileReader wav = new WaveFileReader(ms))// String.Format("{0}\\wav22050\\{1}\\{2}.wav", folder, item.Folder, item.FileName)))
                        {
                            ConvertToWav(item, folder, true, new String[] { Name, SelectedVoice.Name, SelectedDiscreteSpeed, SelectedDiscreteVolume });
                        }
                    }
                }).Start();
            }
            catch (Exception Ex)
            {
                Logger.Log(Ex.ToString());
            }
        }
 //this method takes an actual wav file and converts it
 public static byte[] ConvertWavToMp3(string wavFile, bool deleteWavAfter)
 {
     byte[] mp3bytes = null;
     try
     {
         using (var retMs = new MemoryStream())
         using (var rdr = new WaveFileReader(wavFile))
         using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, bitRate))
         {
             rdr.CopyTo(wtr);
             mp3bytes = retMs.ToArray();
         }
         if(deleteWavAfter)
         {
             File.Delete(wavFile);
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine(e);
     }
     return mp3bytes;
 }
Example #36
0
        protected bool StartWriter(string filePath, WaveFormat waveformat)
        {

            if (Common.CanWriteOnFile(filePath))
            {
                //MP3
                if (this._RecordingFormat == OutputFormat.MP3)
                {
                    try
                    {
                        this._MP3Writer = new LameMP3FileWriter(filePath, waveformat, this._BitRate);
                    }
                    catch(ExternalException e)
                    {
                        MessageBox.Show(e.Message);
                        return false;
                    }
                        
                }
                //WAV
                else if(this._RecordingFormat == OutputFormat.WAV)
                {
                    this._WAVWriter = new WaveFileWriter(filePath, this._Capturer.WaveFormat);
                }

                return true;
            }
            else
            {
                return false;
            }
            
        }
Example #37
0
        private void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename)
        {
            ms.Seek(0, SeekOrigin.Begin);

            using (var rdr = new WaveFileReader(ms))
            using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90))
            {
                rdr.CopyTo(wtr);
            }
        }