Exemple #1
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 #2
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 #3
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 #4
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 #5
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 #6
0
        public override void Process()
        {
            Log.WriteInfoToLog("Starting Process()...");
            var sourceMusicCollection = ReadSourceDirectory();
            var formatter             = AlbumFormatFactory.GetAlbumFormatter(_settings.Format);
            var mp3Writer             = new Mp3Writer(_settings, formatter);

            WriteAlbums(mp3Writer, sourceMusicCollection.Artists);
            Log.WriteInfoToLog("Finished Process()...");
        }
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
        private static void WriteFile(Mp3Writer wmaOutput, WmaStreamReader wmaInput, byte[] buffer, long stopPosition)
        {
            if (stopPosition == -1)
            {
                stopPosition = wmaInput.Length + 1;
            }
            int read;

            //Read the file until we hit our stop position, or the end of the file.
            while (wmaInput.Position < stopPosition && (read = wmaInput.Read(buffer, 0, buffer.Length)) > 0)
            {
                wmaOutput.Write(buffer, 0, read);
            }
        }
Exemple #9
0
        public void Download(Track track)
        {
            counter          = 0;
            downloadingTrack = track;
            var stream     = new FileStream("downloading", FileMode.Create);
            var waveFormat = new WaveFormat(44100, 16, 2);
            var beConfig   = new BE_CONFIG(waveFormat, 320);

            wr = new Mp3Writer(stream, waveFormat, beConfig);
            session.PlayerLoad(track);
            session.PlayerPlay(true);
            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(0);
            }
        }
Exemple #10
0
        public void Download(Track track)
        {
            if (!canPlay(track))
            {
                if (OnDownloadComplete != null)
                {
                    OnDownloadComplete(false);
                }
                return;
            }

            counter          = 0;
            downloadingTrack = track;

            var dir      = downloadPath + escape(downloadingTrack.Album().Name()) + "\\";
            var fileName = dir + escape(GetTrackFullName(downloadingTrack)) + ".mp3";

            if (GetDownloadType() == DownloadType.SKIP && File.Exists(fileName))
            {
                if (OnDownloadProgress != null)
                {
                    OnDownloadProgress(100);
                }

                if (OnDownloadComplete != null)
                {
                    OnDownloadComplete(true);
                }
                return;
            }

            var stream     = new FileStream("downloading", FileMode.Create);
            var waveFormat = new WaveFormat(44100, 16, 2);
            var beConfig   = new BE_CONFIG(waveFormat, 320);

            wr = new Mp3Writer(stream, waveFormat, beConfig);
            session.PlayerLoad(track);
            session.PlayerPlay(true);
            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(0);
            }
        }
        public void Download(Track track)
        {
            if (!CanPlay(track))
            {
                if (OnDownloadComplete != null)
                {
                    OnDownloadComplete(false);
                }
                return;
            }

            _downloadingTrack = track;
            var fileName = getUpdatedTrackName(_downloadingTrack);

            if (GetDownloadType() == DownloadType.SKIP && File.Exists(fileName))
            {
                if (OnDownloadProgress != null)
                {
                    OnDownloadProgress(100);
                }

                if (OnDownloadComplete != null)
                {
                    OnDownloadComplete(true);
                }
                return;
            }

            var stream     = new FileStream("downloading", FileMode.Create);
            var waveFormat = new WaveFormat(44100, 16, 2);
            var beConfig   = new BE_CONFIG(waveFormat, 320);

            _wr = new Mp3Writer(stream, waveFormat, beConfig);
            _session.PlayerLoad(track);
            _session.PlayerPlay(true);
            _session.SetVolumeNormalization(bool.Parse(GUI.frmMain.configuration.GetConfiguration("volume_normalization")));
            if (OnDownloadProgress != null)
            {
                OnDownloadProgress(0);
            }
        }
Exemple #12
0
        public void Start()
        {
            try
            {
                lock (this)
                {
                    if (File.Exists(FileName))
                    {
                        FileStream = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                    }
                    else
                    {
                        FileStream = File.Open(FileName, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                    }

                    switch (FileType)
                    {
                    case eFileType.MP3:
                        Mp3Writer = new Mp3Writer(new WaveFormat((int)OutSamplingRate, 16, 1));
                        break;

                    case eFileType.WAV:
                        WriteHeader(FileStream);
                        break;
                    }

                    NextFlushPosition = FlushDelta;

                    Started         = true;
                    DisplayedStatus = "File opened...";
                    Status          = "";
                }
            }
            catch (Exception e)
            {
                Status          = "(fail)";
                DisplayedStatus = "Failed (" + e.GetType().ToString() + ")";
                return;
            }
        }
Exemple #13
0
        public static void WmaToMp3(Stream wmaInputStream, Stream outputStream, uint bitRate, int bufferMultiplier)
        {
            WmaToMp3Delegate convert = wmaStream =>
            {
                var writer = new Mp3Writer(outputStream,
                                           new Mp3WriterConfig(wmaStream.Format, bitRate));
                var buffer = new byte[writer.OptimalBufferSize * bufferMultiplier];
                WriteToStream(writer, wmaStream, buffer);
            };
            var tempStream = wmaInputStream as WmaStreamReader;

            if (tempStream != null)
            {
                convert(tempStream);
            }
            else
            {
                using (var wmaStream = new WmaStreamReader(wmaInputStream))
                {
                    convert(wmaStream);
                }
            }
        }
Exemple #14
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 #15
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 #16
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);
     }
 }
Exemple #17
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 #18
0
        public void Start()
        {
            if (Listener == null)
            {
                try
                {
                    BE_CONFIG mp3Config = new BE_CONFIG(new WaveFormat((int)SamplingRate, 16, 1));

                    mp3Config.format.lhv1.bEnableVBR   = 1;
                    mp3Config.format.lhv1.dwMaxBitrate = 128;
                    mp3Config.format.lhv1.nMode        = MpegMode.MONO;
                    mp3Config.format.lhv1.nPreset      = LAME_QUALITY_PRESET.LQP_AM;

                    Mp3Writer = new Mp3Writer(mp3Config);
                    Listener  = new TcpListener(IPAddress.Any, 12121);
                    Listener.Start();
                }
                catch (Exception e)
                {
                    Status = "Failed: " + e.GetType().ToString();
                    return;
                }

                AcceptThread = new Thread(() =>
                {
                    while (true)
                    {
                        TcpClient client  = Listener.AcceptTcpClient();
                        Stream stream     = client.GetStream();
                        TextReader reader = new StreamReader(stream);

                        /* wait for request */
                        string line = "";
                        do
                        {
                            line = reader.ReadLine();

                            if (line.ToLower().StartsWith("icy-metadata:"))
                            {
                                SendMetadata = (line.Substring(13).Trim() == "1");
                            }
                        } while (line != "");

                        string header = "";
                        header       += "ICY 200 OK\r\n";
                        header       += "icy-notice1:g3gg0.de\r\n";
                        header       += "icy-notice2:MP3 Stream Node\r\n";
                        header       += "icy-name:RX-FFT MP3 Stream\r\n";
                        header       += "icy-genre:development\r\n";
                        header       += "icy-url:http://g3gg0.de/\r\n";
                        header       += "icy-pub:1\r\n";
                        header       += "icy-br:128\r\n";

                        SendMetadata = false;
                        if (SendMetadata)
                        {
                            header += "icy-metaint:" + MetaInt + "\r\n";
                        }
                        else
                        {
                            header += "icy-metaint:0\r\n";
                        }
                        header += "\r\n";

                        byte[] arr = TextEncoding.GetBytes(header);
                        stream.Write(arr, 0, arr.Length);

                        lock (ClientStreams)
                        {
                            ClientInfo info = new ClientInfo();
                            info.Stream     = stream;
                            info.DataSent   = 0;
                            info.UpdateMeta = true;

                            ClientStreams.AddLast(info);
                            UpdateStatus();
                        }
                    }
                }
                                          );

                AcceptThread.Start();
            }
        }
Exemple #19
0
 private static void WriteFile(Mp3Writer wmaOutput, WmaStreamReader wmaInput, byte[] buffer)
 {
     WriteFile(wmaOutput, wmaInput, buffer, -1);
 }
    /// <summary>
    /// Build all the temp files
    /// </summary>
    /// <remarks>
    /// One of the most hideous functions ever written.  Refactoring would be nice.
    /// </remarks>
    public void CreateTempFiles()
    {
        /* Dev links:
         *
         * http://localhost:82/player/epgcbha - clerks mp3 - id46
         *
         * http://localhost:82/player/dpccbha - beavis wav - id32
         *
         * http://localhost:82/player/dpbcbha - ace losers mp3 - id31
         *
         * http://192.168.1.117:82/player/fqavbha - borat wav - id50 - it is nice - won't convert to mp3
         *
         */


        dynamic theSound     = null;
        Stream  outputStream = new MemoryStream();

        if (_requestInfo.IsValid)   // Functions.IsNumeric(soundId))
        {
            int soundId = _requestInfo.SoundId;

            //
            // First, look in the cache and see if we have a converted mp3 there already
            //
            string targetMp3File = LocalMp3File;    //Functions.CombineElementsWithDelimiter("\\", _targetPath, string.Format("id{0}.mp3", soundId));
            string targetWavFile = LocalWavFile;    // Functions.CombineElementsWithDelimiter("\\", _targetPath, string.Format("id{0}.wav", soundId));

            //if (!NeedToCreateAtLeastOneFile(targetMp3File, targetWavFile))
            if (HaveAtLeastOneFile(targetMp3File, targetWavFile))
            {
                return;
            }
            else
            {
                //
                // OK, let's grab the sound data from the DB
                //
                theSound = GetSoundData(Functions.ConvertInt(soundId, -1));

                if (theSound != null && theSound.Id >= 0)
                {
                    //
                    // The DB returns HTML-ready bytes.  It would be more efficient to return the binary data.  Then we wouldn't have to do 2 conversions.
                    // Todo!
                    //
                    byte[] originalSourceByteArray = System.Convert.FromBase64String(theSound.Data);

                    if (Functions.IsWav(theSound.FileName))
                    {
                        bool successfulWavConversionToMp3 = false;

                        //
                        // It's an wav, convert to mp3
                        //
                        Mp3Writer outputMp3Writer = null;
                        // Mp3Writer outputFileMp3Writer = null;

                        //
                        // These are WaveLib.WaveStream objects that wrap the LAME thing
                        //
                        WaveStream waveDataToConvertToMp3    = null;
                        WaveStream convertedSourceWaveStream = null;
                        WaveStream originalSourceWaveStream  = new WaveStream(new MemoryStream(originalSourceByteArray));

                        try
                        {
                            outputMp3Writer        = new Mp3Writer(outputStream, originalSourceWaveStream.Format);
                            waveDataToConvertToMp3 = originalSourceWaveStream;
                        }
                        catch         // (Exception ex)
                        {
                            outputMp3Writer = null;

                            //
                            // The source WAV isn't compatible with the LAME thingy.  Let's try to convert it to something we know is usable with the NAudio thingy.
                            // Then we'll use the NAudio stuff to try to get the LAME stuff to work.
                            //
                            //MemoryStream tempMemStream = new MemoryStream();
                            int sampleRate = 16000;
                            int bitDepth   = 16;

                            //
                            // Note: there appears to be a bug in the LAME thing for files with 1 channel (mono).  The file plays at double speed.
                            //
                            int channels = 2;
                            NAudio.Wave.WaveFormat targetFormat = new NAudio.Wave.WaveFormat(sampleRate, bitDepth, channels);

                            NAudio.Wave.WaveStream stream = new NAudio.Wave.WaveFileReader(new MemoryStream(originalSourceByteArray));
                            NAudio.Wave.WaveFormatConversionStream str = null;

                            try
                            {
                                str = new NAudio.Wave.WaveFormatConversionStream(targetFormat, stream);
                            }
                            catch (Exception ex3)
                            {
                                //
                                // The borat "It is nice" WAV won't convert, has strange exception.  Todo: add logging and fix.
                                //
                                ErrorMsg = string.Format("Well, naudio can't convert the WAV to the target WAV format either: {0}", ex3.Message);
                            }

                            if (str != null)
                            {
                                //
                                // For lack of a better solution to get the bytes from the converted data into a "WaveStream" variable, use these
                                // available methods to write to a disk file and then open up the disk file.  The problem with directly converting
                                // with memory streams is that the required headers (like "RIFF") aren't written into the converted stream at this point.
                                //
                                NAudio.Wave.WaveFileWriter.CreateWaveFile(targetWavFile, str);
                                convertedSourceWaveStream = new WaveStream(targetWavFile);

                                //
                                // Now we have a correct WAV memory stream
                                //
                                try
                                {
                                    WaveFormat format = convertedSourceWaveStream.Format;
                                    outputMp3Writer        = new Mp3Writer(outputStream, format);
                                    waveDataToConvertToMp3 = convertedSourceWaveStream;
                                }
                                catch (Exception ex2)
                                {
                                    //
                                    // Crap, I think we're hosed
                                    //
                                    ErrorMsg = string.Format("Oops - second try - can't process this file: {0}", ex2.Message);
                                }
                            }
                        }


                        if (outputMp3Writer != null)
                        {
                            //
                            // If we're here, we've successfully created the MP3 converter from the WAV file, and our data stream
                            // is in the variable "waveDataToConvertToMp3"
                            //
                            try
                            {
                                byte[] buff = new byte[outputMp3Writer.OptimalBufferSize];
                                int    read = 0;
                                while ((read = waveDataToConvertToMp3.Read(buff, 0, buff.Length)) > 0)
                                {
                                    outputMp3Writer.Write(buff, 0, read);
                                }

                                //
                                // We have mp3 bytes, write 'em
                                //
                                // FileStream outputMp3File = new FileStream(targetMp3File, FileMode.CreateNew);
                                //outputMp3File.Write(originalSourceByteArray, 0, originalSourceByteArray.Length);
                                using (Stream outputMp3File = File.OpenWrite(targetMp3File))
                                {
                                    outputStream.Position = 0;
                                    Functions.CopyStream(outputStream, outputMp3File);
                                }

                                successfulWavConversionToMp3 = true;
                            }
                            catch (Exception ex)
                            {
                                ErrorMsg = string.Format("Oops, fatal error: {0}", ex.Message);
                            }
                            finally
                            {
                                outputMp3Writer.Close();
                                waveDataToConvertToMp3.Close();
                            }
                        }

                        if (!successfulWavConversionToMp3)
                        {
                            //
                            // Well, everthing failed.  We have a WAV at least, let's go ahead and write that.
                            //
                            File.WriteAllBytes(targetWavFile, originalSourceByteArray);
                        }

                        //
                        // Let's clean this stuff up
                        //
                        originalSourceWaveStream.Close();

                        if (convertedSourceWaveStream != null)
                        {
                            convertedSourceWaveStream.Close();
                        }
                    }
                    else
                    {
                        FileStream outputMp3File = null;
                        try
                        {
                            outputMp3File = new FileStream(targetMp3File, FileMode.CreateNew);
                            //
                            // We have mp3 bytes, write 'em
                            //
                            outputMp3File.Write(originalSourceByteArray, 0, originalSourceByteArray.Length);
                        }
                        catch
                        {
                            // Maybe we have the file already by another thread?
                            ErrorMsg = "Have mp3, can't write to disk.";
                        }
                        finally
                        {
                            if (outputMp3File != null)
                            {
                                outputMp3File.Close();
                            }
                        }

                        /*
                         * Huge todo: this code works fine on Windows 7, but doesn't work on Windows 2008 Server.  The problem is two fold:
                         *
                         *  a) The two mp3 encoders installed by Win7 (l3codeca.acm and l3codecp.acm) don't exist.  I see no way to "install" them.
                         *      This site comes closes to explaining, but these reg keys do NOT exist so the solution doesn't work:
                         *      http://blog.komeil.com/2008/06/enabling-fraunhofer-mp3-codec-vista.html
                         *
                         *  b) The alternate option explained here:
                         *      http://stackoverflow.com/questions/5652388/naudio-error-nodriver-calling-acmformatsuggest/5659266#5659266
                         *      Also doesn't work since the COM object for the DMO isn't registered on Win2K8.  The Windows SDK is supposed to have it,
                         *      but it doesn't install properly on the server.  Also Win Media Player won't install with a weird "There is no update to Windows Media Player".
                         *
                         *  I've googled for a long time, but this is a tricky one.  Maybe Microsoft needs to be contacted?
                         *
                         * This is required to create WAV files for Firefox to play.  Otherwise you have to click on a link. (alt solution: embed?)
                         *
                         *                      NAudio.Wave.Mp3FileReader reader = null;
                         *                      try
                         *                      {
                         *                              //
                         *                              // Let's write the WAV bytes
                         *                              // http://hintdesk.com/c-mp3wav-converter-with-lamenaudio/
                         *                              //
                         *                              using (reader = new NAudio.Wave.Mp3FileReader(targetMp3File))
                         *                              {
                         *                                      using (NAudio.Wave.WaveStream pcmStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(reader))
                         *                                      {
                         *                                              NAudio.Wave.WaveFileWriter.CreateWaveFile(targetWavFile, pcmStream);
                         *                                      }
                         *                              }
                         *                      }
                         *                      catch
                         *                      {
                         *                              ErrorMsg = "Have mp3, can't convert to WAV";
                         *                      }
                         *                      finally
                         *                      {
                         *                              if (reader != null)
                         *                              {
                         *                                      reader.Close();
                         *                              }
                         *                      }
                         *
                         */
                    }
                }
                else
                {
                    ErrorMsg = "Cannot get sound id";
                }
            }
        }
        else
        {
            ErrorMsg = string.Format("Invalid request parameter: {0}", _encryptedPlayerRequest);
        }
    }
Exemple #21
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);
            }
        }