Exemple #1
0
        internal byte[] ConvertWavToMp3(Stream stream)
        {
            var inStr = new WaveStream(stream);

            try {
                var convertedStream = new MemoryStream();
                var writer          = new Mp3Writer(convertedStream, inStr.Format);
                try {
                    var buff = new byte[writer.OptimalBufferSize];
                    int read;
                    while ((read = inStr.Read(buff, 0, buff.Length)) > 0)
                    {
                        writer.Write(buff, 0, read);
                    }

                    convertedStream.Seek(0, SeekOrigin.Begin);
                    return(convertedStream.ToArray());
                } catch (Exception e) {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorException(
                        "AudioConverter.ConvertWavToMp3 inner вылетело исключение {0}", e);
                } finally {
                    writer.Close();
                }
            } catch (Exception e) {
                LoggerWrapper.LogTo(LoggerName.Errors).ErrorException(
                    "AudioConverter.ConvertWavToMp3 outer вылетело исключение {0}", e);
            } finally {
                inStr.Close();
            }
            return(null);
        }
Exemple #2
0
        /// <summary>
        /// Converts Wav to MP3.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputPath">The output path.</param>
        /// <returns>
        /// Path of changed file
        /// </returns>
        public static string ConvertWavToMp3(string inputFile, string outputPath)
        {
            var reader = new WaveStream(inputFile);

            try
            {
                var config = new BE_CONFIG(reader.Format, (uint)(Math.Abs(BitRate - 0.0) < 0.1 ? DefaultBitRate : BitRate));
                var writer = new Mp3Writer(new FileStream(outputPath, FileMode.Create), reader.Format, config);

                try
                {
                    var buffer = new byte[writer.OptimalBufferSize];
                    int read;
                    while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        writer.Write(buffer, 0, read);
                    }
                }
                finally
                {
                    writer.Close();
                }
            }
            finally
            {
                reader.Close();
            }

            return(outputPath);
        }
Exemple #3
0
        public void Stop()
        {
            lock (this)
            {
                if (FileStream != null)
                {
                    switch (FileType)
                    {
                    case eFileType.MP3:
                        break;

                    case eFileType.WAV:
                        WriteHeader(FileStream);
                        break;
                    }
                    FileStream.Close();
                    FileStream = null;
                }
                if (Mp3Writer != null)
                {
                    Mp3Writer.Close();
                    Mp3Writer = null;
                }

                Started         = false;
                Status          = "";
                DisplayedStatus = "File closed...";
            }
        }
Exemple #4
0
        private static void mp3izza(string nomefile, string nomefilemp3)
        {
            WaveStream filewav = new WaveStream(nomefile);
            //      try
            //      {
            Mp3Writer salvamp3 = new Mp3Writer(new FileStream(nomefilemp3,
                                                              FileMode.Create), filewav.Format);

            //          try
            //          {
            byte[] buff = new byte[salvamp3.OptimalBufferSize];
            int    read = 0;

            while ((read = filewav.Read(buff, 0, buff.Length)) > 0)
            {
                salvamp3.Write(buff, 0, read);
            }
            //         }
            //         finally
            //         {
            salvamp3.Close();
            //         }
            //     }
            //     finally
            //     {
            filewav.Close();
            //     }
            File.Delete(nomefile);
        }
Exemple #5
0
        /// <summary>
        /// Combines files into one in the order they are passed in..
        /// </summary>
        /// <param name="bufferMultiplier">The multiplier to use against the OptimalBufferSize of the file for the read buffer, sometimes a larger than optimal buffer size is better.</param>
        /// <param name="inputStreams">The streams to combine</param>
        /// <param name="outputStream">The stream to save the combined file to.</param>
        public static void Combine(Stream outputStream, int bufferMultiplier, params Stream[] inputStreams)
        {
            if (inputStreams.Length <= 0)
            {
                return;
            }

            var wmaInput = inputStreams[0] is WmaStreamReader
                ? (WmaStreamReader)inputStreams[0]
                : new WmaStreamReader(inputStreams[0]);

            var wmaOutput = new Mp3Writer(outputStream,
                                          wmaInput.Format,
                                          new BE_CONFIG(wmaInput.Format, (uint)GetBitRate(wmaInput.Format.nAvgBytesPerSec / 1024)));

            var buffer = new byte[wmaOutput.OptimalBufferSize * bufferMultiplier];

            try
            {
                WriteFile(wmaOutput, wmaInput, buffer);
                for (var i = 1; i < inputStreams.Length; i++)
                {
                    wmaInput = inputStreams[i] is WmaStreamReader
                        ? (WmaStreamReader)inputStreams[i]
                        : new WmaStreamReader(inputStreams[i]);
                    WriteFile(wmaOutput, wmaInput, buffer);
                }
            }
            finally
            {
                wmaOutput.Close();
            }
        }
Exemple #6
0
        public override async void EndOfTrack(SpotifySession session)
        {
            session.PlayerPlay(false);
            wr.Close();

            // Move File
            var dir = downloadPath + escape(downloadingTrack.Album().Name()) + "\\";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var fileName = dir + escape(GetTrackFullName(downloadingTrack)) + ".mp3";

            if (GetDownloadType() == DownloadType.OVERWRITE && File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            File.Move("downloading", fileName);

            // Tag
            var u = new UltraID3();

            u.Read(fileName);
            u.Artist   = GetTrackArtistsNames(downloadingTrack);
            u.Title    = downloadingTrack.Name();
            u.Album    = downloadingTrack.Album().Name();
            u.TrackNum = (short)downloadingTrack.Index();
            u.Year     = (short)downloadingTrack.Album().Year();

            var imageID = downloadingTrack.Album().Cover(ImageSize.Large);
            var image   = SpotifySharp.Image.Create(session, imageID);

            await WaitForBool(image.IsLoaded);

            var tc  = TypeDescriptor.GetConverter(typeof(Bitmap));
            var bmp = (Bitmap)tc.ConvertFrom(image.Data());

            var pictureFrame = new ID3v23PictureFrame(bmp, PictureTypes.CoverFront, "image", TextEncodingTypes.ISO88591);

            u.ID3v2Tag.Frames.Add(pictureFrame);

            u.Write();

            base.EndOfTrack(session);

            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(100);
            }

            if (OnDownloadComplete != null)
            {
                OnDownloadComplete(true);
            }
        }
Exemple #7
0
        public static void ConvertWavToMp3(string wav, string mp3)
        {
            Mp3WriterConfig m_Config = null;
            WaveStream      InStr    = new WaveStream(wav);

            m_Config = new Mp3WriterConfig(InStr.Format);
            m_Config.Mp3Config.format.mp3.bOriginal = 80;

            try
            {
                Mp3Writer writer = new Mp3Writer(new FileStream(mp3, FileMode.Create), m_Config);

                try
                {
                    byte[] buff   = new byte[writer.OptimalBufferSize];
                    int    read   = 0;
                    int    actual = 0;
                    long   total  = InStr.Length;

                    try
                    {
                        while ((read = InStr.Read(buff, 0, buff.Length)) > 0)
                        {
                            writer.Write(buff, 0, read);
                            actual += read;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                InStr.Close();
            }
        }
Exemple #8
0
        public void convert_mp3(string wavPath)
        {
            string[] wavFiles = Directory.GetFiles(wavPath, "*.wav");
            foreach (string w in wavFiles)
            {
                string sPath = Path.GetDirectoryName(w);
                string fName = Path.GetFileNameWithoutExtension(w);
                #region write mp3
                WaveStream InStr = new WaveStream(w);
                try
                {
                    Mp3Writer writer = new Mp3Writer(new FileStream(sPath + "\\" + fName + ".mp3",
                                                                    FileMode.Create), InStr.Format);
                    try
                    {
                        byte[] buff = new byte[writer.OptimalBufferSize];
                        int    read = 0;
                        while ((read = InStr.Read(buff, 0, buff.Length)) > 0)
                        {
                            writer.Write(buff, 0, read);
                        }
                    }
                    finally
                    {
                        writer.Close();
                    }
                }
                finally
                {
                    InStr.Close();
                }

                #endregion
                File.Delete(w);
            }
        }
Exemple #9
0
        /// <summary>
        /// Cuts out a smaller portion of a Wma file.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <param name="outputStream">The stream to write the split portion to.</param>
        /// <param name="startTime">The time that the split from the source stream should start.</param>
        /// <param name="endTime">The time that the split from the source stream should end.</param>
        /// <param name="bufferMultiplier">The multiplier to use against the OptimalBufferSize of the file for the read buffer, sometimes a larger than optimal buffer size is better.</param>
        public static void Split(Stream inputStream, Stream outputStream, TimeSpan startTime, TimeSpan endTime, int bufferMultiplier)
        {
            var wmaInput    = inputStream is WmaStreamReader ? (WmaStreamReader)inputStream : new WmaStreamReader(inputStream);
            int bytesPerSec = wmaInput.Format.nAvgBytesPerSec;

            var wmaOutput = new Mp3Writer(outputStream, wmaInput.Format,
                                          new BE_CONFIG(wmaInput.Format, (uint)GetBitRate(bytesPerSec / 1024)));
            var stopPosition = (long)(bytesPerSec * endTime.TotalSeconds);
            var buffer       = new byte[wmaOutput.OptimalBufferSize * bufferMultiplier];

            var offset = (long)(bytesPerSec * startTime.TotalSeconds);

            offset = offset - (offset % wmaInput.SeekAlign);

            wmaInput.Seek(offset, SeekOrigin.Begin);
            try
            {
                WriteFile(wmaOutput, wmaInput, buffer, stopPosition);
            }
            finally
            {
                wmaOutput.Close();
            }
        }
Exemple #10
0
 private void buttonCompress_Click(object sender, System.EventArgs e)
 {
     if (File.Exists(textBoxOutFile.Text) && (MessageBox.Show(this, "Override the existing file?", "File exists", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes))
     {
         return;
     }
     try
     {
         progressBar.Value = 0;
         toolTip1.SetToolTip(progressBar, "");
         this.Text   = "Audio Compress";
         Compressing = true;
         try
         {
             RefreshControls();
             WaveStream InStr = new WaveStream(textBoxInFile.Text);
             try
             {
                 Mp3Writer writer = new Mp3Writer(new FileStream(textBoxOutFile.Text, FileMode.Create), m_Config);
                 try
                 {
                     byte[] buff   = new byte[writer.OptimalBufferSize];
                     int    read   = 0;
                     int    actual = 0;
                     long   total  = InStr.Length;
                     Cursor.Current = Cursors.WaitCursor;
                     try
                     {
                         while ((read = InStr.Read(buff, 0, buff.Length)) > 0)
                         {
                             Application.DoEvents();
                             writer.Write(buff, 0, read);
                             actual           += read;
                             progressBar.Value = (int)(((long)actual * 100) / total);
                             toolTip1.SetToolTip(progressBar, string.Format("{0}% compresssed", progressBar.Value));
                             this.Text = string.Format("Audio Compress - {0}% compresssed", progressBar.Value);
                             Application.DoEvents();
                         }
                         toolTip1.SetToolTip(progressBar, "Done");
                         this.Text = "Audio Compress - Done";
                     }
                     finally
                     {
                         Cursor.Current = Cursors.Default;
                     }
                 }
                 finally
                 {
                     writer.Close();
                 }
             }
             finally
             {
                 InStr.Close();
             }
         }
         finally
         {
             Compressing = false;
             RefreshControls();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "An exception has ocurred with the following message", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public override async void EndOfTrack(SpotifySession session)
        {
            session.PlayerPlay(false);
            _wr.Close();

            // Move File
            var fileName = getUpdatedTrackName(_downloadingTrack);

            if (GetDownloadType() == DownloadType.OVERWRITE && File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            var dir = Path.GetDirectoryName(fileName);

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

            File.Move("downloading", fileName);

            // Tags
            var file = TagLib.File.Create(fileName);

            file.Tag.Title        = _downloadingTrack.Name();
            file.Tag.Performers   = new[] { GetTrackArtistsNames(_downloadingTrack) };
            file.Tag.Disc         = (uint)_downloadingTrack.Disc();
            file.Tag.Year         = (uint)_downloadingTrack.Album().Year();
            file.Tag.Track        = (uint)_downloadingTrack.Index();
            file.Tag.Album        = _downloadingTrack.Album().Name();
            file.Tag.Comment      = Link.CreateFromTrack(_downloadingTrack, 0).AsString();
            file.Tag.AlbumArtists = new string[] { _downloadingTrack.Album().Artist().Name() };

            // Download img
            Bitmap bmp = await DownloadImage(_downloadingTrack, 0);


            // Set img
            var pic = new TagLib.Picture();

            pic.Type        = TagLib.PictureType.FrontCover;
            pic.Description = "Cover";
            pic.MimeType    = System.Net.Mime.MediaTypeNames.Image.Jpeg;
            var ms = new MemoryStream();

            if (bmp != null)
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Position       = 0;
                pic.Data          = TagLib.ByteVector.FromStream(ms);
                file.Tag.Pictures = new TagLib.IPicture[] { pic };
            }

            // Save
            file.Save();

            base.EndOfTrack(session);

            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(100);
            }

            if (OnDownloadComplete != null)
            {
                OnDownloadComplete(true);
            }
        }
Exemple #12
0
        private static void SaveTrack(TrackInfo trackInfo)
        {
            string targetFileName = trackInfo.MusicTag.Title;

            if (m_Drive.Open(trackInfo.Item.Path[0]))
            {
                char[] Drives = CDDrive.GetCDDriveLetters();
                if ((Array.IndexOf(Drives, trackInfo.Item.Path[0]) > -1) && (m_Drive.IsCDReady()) && (m_Drive.Refresh()))
                {
                    try
                    {
                        m_Drive.LockCD();
                        if (dlgProgress.IsCanceled)
                        {
                            m_CancelRipping = true;
                        }
                        if (!m_CancelRipping)
                        {
                            try
                            {
                                try
                                {
                                    WaveFormat Format    = new WaveFormat(44100, 16, 2);
                                    BE_CONFIG  mp3Config = new BE_CONFIG(Format);
                                    if (mp3VBR)
                                    {
                                        mp3Config.format.lhv1.bEnableVBR = 1;
                                        if (mp3FastMode)
                                        {
                                            mp3Config.format.lhv1.nVbrMethod = VBRMETHOD.VBR_METHOD_NEW;
                                        }
                                        else
                                        {
                                            mp3Config.format.lhv1.nVbrMethod = VBRMETHOD.VBR_METHOD_DEFAULT;
                                        }
                                        mp3Config.format.lhv1.nVBRQuality = mp3Quality;
                                    }
                                    else if (mp3CBR)
                                    {
                                        mp3Config.format.lhv1.bEnableVBR = 0;
                                        mp3Config.format.lhv1.nVbrMethod = VBRMETHOD.VBR_METHOD_NONE;
                                        mp3Config.format.lhv1.dwBitrate  = Convert.ToUInt16(Rates[mp3BitRate]);
                                    }
                                    else
                                    {
                                        mp3Config.format.lhv1.bEnableVBR = 1;
                                        mp3Config.format.lhv1.nVbrMethod = VBRMETHOD.VBR_METHOD_ABR;
                                        uint ConToKbwVbrAbr_bps = Convert.ToUInt16(Rates[mp3BitRate]);
                                        mp3Config.format.lhv1.dwVbrAbr_bps = ConToKbwVbrAbr_bps * 1000;
                                    }

                                    if (mp3MONO)
                                    {
                                        mp3Config.format.lhv1.nMode = MpegMode.MONO;
                                    }

                                    mp3Config.format.lhv1.bWriteVBRHeader = 1;

                                    Stream WaveFile = new FileStream(trackInfo.TempFileName, FileMode.Create, FileAccess.Write);
                                    m_Writer = new Mp3Writer(WaveFile, Format, mp3Config);
                                    if (!m_CancelRipping)
                                    {
                                        try
                                        {
                                            Log.Info("CDIMP: Processing track {0}", trackInfo.MusicTag.Track);

                                            DateTime InitTime = DateTime.Now;
                                            if (
                                                m_Drive.ReadTrack(trackInfo.MusicTag.Track, new CdDataReadEventHandler(WriteWaveData),
                                                                  new CdReadProgressEventHandler(CdReadProgress)) > 0)
                                            {
                                                if (dlgProgress.IsCanceled)
                                                {
                                                    m_CancelRipping = true;
                                                }
                                                if (!m_CancelRipping)
                                                {
                                                    TimeSpan Duration = DateTime.Now - InitTime;
                                                    double   Speed    = m_Drive.TrackSize(trackInfo.MusicTag.Track) / Duration.TotalSeconds /
                                                                        Format.nAvgBytesPerSec;
                                                    Log.Info("CDIMP: Done reading track {0} at {1:0.00}x speed", trackInfo.MusicTag.Track, Speed);
                                                }
                                            }
                                            else
                                            {
                                                Log.Info("CDIMP: Error reading track {0}", trackInfo.MusicTag.Track);
                                                m_Writer.Close();
                                                WaveFile.Close();
                                                if (File.Exists(trackInfo.TempFileName))
                                                {
                                                    try
                                                    {
                                                        File.Delete(trackInfo.TempFileName);
                                                    }
                                                    catch {}
                                                }
                                                //progressBar1.Value = 0;
                                            }
                                        }
                                        finally
                                        {
                                            m_Writer.Close();
                                            m_Writer = null;
                                            WaveFile.Close();
                                            Lame_encDll.beWriteVBRHeader(trackInfo.TempFileName);
                                        }
                                    }
                                }
                                finally {}
                            }
                            finally
                            {
                                m_Drive.Close();
                            }
                        }
                    }
                    finally
                    {
                        //progressBar1.Value = 0;
                    }
                }
                if (dlgProgress.IsCanceled)
                {
                    m_CancelRipping = true;
                }
                if (m_CancelRipping)
                {
                    if (File.Exists(trackInfo.TempFileName))
                    {
                        File.Delete(trackInfo.TempFileName);
                    }
                    m_Drive.Close();
                }
            }
        }
Exemple #13
0
        // convert to MP3
        private void ConvertToMP3(String f, String FileName, int LocType)
        {
            try
            {
                WaveReader wr        = new WaveReader(File.OpenRead(f));
                IntPtr     oldFormat = wr.ReadFormat();
                byte[]     oldData   = wr.ReadData();
                wr.Close();

                if (FileName != "0")
                {
                    f = FileName;
                }

                // if voip, write to voip dir otherwise write to MP3 (N7 & iLink) dir
                if (LocType == 2)
                {
                    textBox1.Text = textBox2.Text;
                }
                else
                {
                    textBox1.Text = textBox1.Text;
                }

                if (File.Exists(textBox1.Text + Path.GetFileName(f)))
                {
                    File.Delete(textBox1.Text + Path.GetFileName(f));
                }
                //txtStatus.Text += f + eol;

                IntPtr pcmFormat = AudioCompressionManager.GetCompatibleFormat(oldFormat,
                                                                               AudioCompressionManager.PcmFormatTag);
                byte[] pcmData = AudioCompressionManager.Convert(oldFormat, pcmFormat, oldData, false);

                IntPtr mp3Format = AudioCompressionManager.GetMp3Format(1, 112, 44100);

                f = f.Replace("wav", "mp3");

                Mp3Writer mw = new Mp3Writer(File.Create(textBox1.Text + Path.GetFileName(f)));

                byte[] newData = AudioCompressionManager.Convert(pcmFormat, mp3Format, oldData, false);
                mw.WriteData(newData);
                mw.Close();

                // **** debug *****
                //TextOps(dirMp3 + Path.GetFileName(f) + eol2);

                //DeleteFile(f);
            }
            catch (NullReferenceException nex)
            {
                //TextOps("NullReferenceException: " + nex.Message.ToString() + cr);
            }
            catch (IOException iex)
            {
                //TextOps("IOException: " + iex.Message.ToString() + cr);
            }
            catch (AudioException ex)
            {
                //TextOps("AudioException: " + ex.Message.ToString() + cr);
            }
        }