Exemple #1
0
        public static Stream ConvertWavToMp3(Stream wavStream)
        {
            _uniqueTempFileCounter += 1;
            var tempFile = Path.GetTempFileName();

            using (var rdr = new WaveFileReader(wavStream))
            {
                if (rdr.WaveFormat.BitsPerSample == 24)                                                           //Can't go from 24 bits wav to mp3 directly, create temporary 16 bit wav
                {
                    ISampleProvider sampleprovider = new Pcm24BitToSampleProvider(rdr);                           //24 bit to sample
                    var             resampler      = new WdlResamplingSampleProvider(sampleprovider, SampleRate); //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else if (!SupportedMPEGSampleRates.Contains(rdr.WaveFormat.SampleRate))                           //Can't go from unsupported Sample Rate wav to mp3 directly
                {
                    var resampler = new WdlResamplingSampleProvider(rdr.ToSampleProvider(), SampleRate);          //sample to new sample rate
                    WaveFileWriter.CreateWaveFile16(tempFile, resampler);                                         //sample to actual wave file
                    return(ConvertWavFileToMp3MemoryStream(tempFile, true));                                      //file to mp3 bytes
                }
                else
                {
                    var retMs = FilesystemUtils.recyclableMemoryStreamManager.GetStream();
                    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, BitRate))
                    {
                        rdr.CopyTo(wtr);
                        return(retMs);
                    }
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Create mp3 from file name
        /// </summary>
        /// <param name="fileName">The output mp3 file name</param>
        /// <param name="fileFull">Full image path</param>
        public void createMp3(string fileName, string fileFull)
        {
            model.bmpName = fileName.Replace(".bmp", "");

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


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

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

                    using (var retMs = File.OpenWrite(OutDirectory + "\\" + fileName + ".mp3"))
                        using (var rdr = new WaveFileReader(ms))
                            using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
                            {
                                rdr.CopyTo(wtr);
                            }
                }
            }
        }
Exemple #3
0
        public void convert(string filepath)
        {
            Mime   mime     = new Mime();
            string mimeType = mime.Lookup(filepath);

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

            Debug.WriteLine(mp3path);

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

                using (MemoryStream memoryStream = new MemoryStream())
                    using (MemoryStream WaveMemoryStream = new MemoryStream(wavFile))
                        using (WaveFileReader WaveFileReader = new WaveFileReader(WaveMemoryStream))
                            using (LameMP3FileWriter mp3Writer = new LameMP3FileWriter(memoryStream, WaveFileReader.WaveFormat, 128)) {
                                WaveFileReader.CopyTo(mp3Writer);
                                try {
                                    File.WriteAllBytes(mp3path, memoryStream.ToArray());
                                } catch (Exception e) {
                                    // error writing file
                                    Debug.WriteLine(e);
                                }
                            }
            } catch (Exception e) {
                Debug.WriteLine(e);
            }
        }
Exemple #4
0
        public XElement AddWaveStreamAsMp3(Stream waveStream, Uri uri, string itemId = null)
        {
            if (waveStream == null)
            {
                throw new ArgumentNullException(nameof(waveStream));
            }
            using (var reader = new WaveFileReader(waveStream))
            {
                using (var mp3Stream = Publication.CreateContainerStream(uri))
                {
                    var writer = new LameMP3FileWriter(mp3Stream, AudioWaveFormat, Mp3BitRate);
                    reader.CopyTo(writer);
                    writer.Close();
                }
            }
            var item = new XElement(
                OpfNs + "item",
                new XAttribute("href", Publication.PackageFileUri.MakeRelativeUri(uri)),
                new XAttribute("media-type", "audio/mpeg"));

            if (!String.IsNullOrEmpty(itemId))
            {
                item.SetAttributeValue("id", itemId);
            }
            return(item);
        }
Exemple #5
0
 private byte[] GenerateMp3(Song song)
 {
     if (song.Notes == null)
     {
         return(null);
     }
     using (var generatedSongStream = new MemoryStream())
     {
         var mp3File  = new MemoryStream();
         var waveFile = new WaveFile(22050, BitDepth.Bit16, 1, generatedSongStream);
         var sg       = new SoundGenerator(waveFile);
         foreach (var note in song.Notes)
         {
             sg.AddSimpleTone(note.Frequency, note.Duration);
         }
         sg.Save();
         generatedSongStream.Position = 0;
         var r  = new WaveFileReader(generatedSongStream);
         var wr = new LameMP3FileWriter(mp3File, r.WaveFormat, 96);
         r.CopyTo(wr);
         wr.Flush();
         var fileData = mp3File.ToArray();
         mp3File.Dispose();
         r.Dispose();
         wr.Dispose();
         return(fileData);
     }
 }
Exemple #6
0
        public static void WriteSong(string waveFileName, string mp3FileName, SongInfo info)
        {
            using (AudioFileReader reader = new AudioFileReader(waveFileName)) {
                //Console.WriteLine(reader.WaveFormat.BitsPerSample);
                WaveFormat format = WaveFormat.CreateIeeeFloatWaveFormat(reader.WaveFormat.SampleRate, reader.WaveFormat.Channels);                //new WaveFormat(reader.WaveFormat.SampleRate, 16, 2)
                using (var resampler = new MediaFoundationResampler(reader, format)) {
                    // resampler.ResamplerQuality = 60;
                    WaveFileWriter.CreateWaveFile(Path.GetFileNameWithoutExtension(mp3FileName) + ".wav", resampler);
                }
            }

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

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

            TagLib.File f = TagLib.File.Create(mp3FileName);
            f.Tag.Album        = info.Album;
            f.Tag.Artists      = new string[] { info.Artist };
            f.Tag.AlbumArtists = new string[] { info.Artist };
            f.Tag.Title        = info.Title;
            f.Tag.Genres       = new string[] { "Soundtrack" };
            f.Tag.Track        = (uint)info.TrackNumber;
            f.Save();
        }
Exemple #7
0
 static async Task <bool> To_MP3(int File_Number, string To_Dir, bool IsFromFileDelete)
 {
     if (!File.Exists(From_Files[File_Number]))
     {
         return(false);
     }
     try
     {
         string To_Audio_File = To_Dir + "\\" + Path.GetFileNameWithoutExtension(From_Files[File_Number]) + ".mp3";
         await Task.Run(() =>
         {
             string Ex = Path.GetExtension(From_Files[File_Number]);
             if (Ex == ".ogg")
             {
                 using (NAudio.Vorbis.VorbisWaveReader reader = new NAudio.Vorbis.VorbisWaveReader(From_Files[File_Number]))
                     using (LameMP3FileWriter wtr = new LameMP3FileWriter(To_Audio_File, reader.WaveFormat, 128))
                         reader.CopyTo(wtr);
             }
             else if (Ex == ".wav")
             {
                 using (WaveFileReader reader = new WaveFileReader(From_Files[File_Number]))
                     using (LameMP3FileWriter wtr = new LameMP3FileWriter(To_Audio_File, reader.WaveFormat, 128))
                         reader.CopyTo(wtr);
             }
             else if (Ex == ".flac")
             {
                 using (NAudio.Flac.FlacReader reader = new NAudio.Flac.FlacReader(From_Files[File_Number]))
                     using (LameMP3FileWriter wtr = new LameMP3FileWriter(To_Audio_File, reader.WaveFormat, 128))
                         reader.CopyTo(wtr);
             }
             else if (Ex == ".aac" || Ex == ".wma" || Ex == ".mp4" || Ex == ".webm")
             {
                 using (MediaFoundationReader reader = new MediaFoundationReader(From_Files[File_Number]))
                     using (LameMP3FileWriter wtr = new LameMP3FileWriter(To_Audio_File, reader.WaveFormat, 128))
                         reader.CopyTo(wtr);
             }
             else
             {
                 Un4seen.Bass.Misc.EncoderLAME mc = new Un4seen.Bass.Misc.EncoderLAME(0);
                 mc.EncoderDirectory = Voice_Set.Special_Path + "/Encode_Mp3";
                 mc.InputFile        = From_Files[File_Number];
                 mc.OutputFile       = To_Audio_File;
                 mc.LAME_Bitrate     = (int)Un4seen.Bass.Misc.EncoderLAME.BITRATE.kbps_160;
                 mc.LAME_Mode        = Un4seen.Bass.Misc.EncoderLAME.LAMEMode.Default;
                 mc.LAME_Quality     = Un4seen.Bass.Misc.EncoderLAME.LAMEQuality.Q2;
                 Un4seen.Bass.Misc.BaseEncoder.EncodeFile(mc, null, true, false, true);
             }
             if (IsFromFileDelete)
             {
                 File.Delete(From_Files[File_Number]);
             }
         });
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Exemple #8
0
        /// <summary>
        /// Convert a WAV into MP3 file
        /// </summary>
        /// <param name="inputFile">Input WAV files path</param>
        /// <param name="outputFile">Output MP3 file path</param>
        /// <param name="id3Tag">MP3 tags</param>
        public static void WavToMp3(string inputFile, string outputFile, ID3TagData id3Tag)
        {
            var reader = new WaveFileReader(inputFile);
            var writer = new LameMP3FileWriter(outputFile, reader.WaveFormat, ExportQuality, id3Tag);

            reader.CopyTo(writer);
            writer.Close();
            reader.Close();
        }
Exemple #9
0
 private static void ConvertWavStreamToMp3File(string outputFile, byte[] waveFile)
 {
     using (var ms = new MemoryStream(waveFile))
         using (var wfr = new WaveFileReader(ms))
             using (var wtr = new LameMP3FileWriter(outputFile, wfr.WaveFormat, LAMEPreset.VBR_100))
             {
                 wfr.CopyTo(wtr);
             }
 }
        public static void GenerateAudioFile(string inFile, string outFile, decimal effectiveMultiplier, bool changePitch = false, bool preDT = false, bool highQuality = false)
        {
            decimal DTCompensatedMultiplier = effectiveMultiplier / 1.5M;

            string temp1 = Path.Combine(Guid.NewGuid().ToString() + ".mp3"); // audio copy
            string temp2 = Path.Combine(Guid.NewGuid().ToString() + ".wav"); // decoded wav
            string temp3 = Path.Combine(Guid.NewGuid().ToString() + ".wav"); // stretched file

            File.Copy(inFile, temp1);

            // mp3 => wav
            using (Mp3FileReader mp3 = new Mp3FileReader(temp1))
                using (WaveStream wav = WaveFormatConversionStream.CreatePcmStream(mp3))
                    WaveFileWriter.CreateWaveFile(temp2, wav);


            // stretch (or speed up) wav
            string quick = highQuality ? "" : "-quick";
            string naa   = highQuality ? "" : "-naa";

            decimal multiplier = preDT ? DTCompensatedMultiplier : effectiveMultiplier;
            string  tempo      = $"-tempo={(multiplier - 1) * 100}";

            decimal cents     = (decimal)(1200.0 * Math.Log((double)effectiveMultiplier) / Math.Log(2));
            decimal semitones = cents / 100.0M;
            string  pitch     = changePitch ? $"-pitch={semitones}" : "";

            Process soundstretch = new Process();

            soundstretch.StartInfo.FileName  = Path.Combine("binaries", "soundstretch.exe");
            soundstretch.StartInfo.Arguments = $"\"{temp2}\" \"{temp3}\" {quick} {naa} {tempo} {pitch}";
            Console.WriteLine(soundstretch.StartInfo.Arguments);
            soundstretch.StartInfo.UseShellExecute = false;
            soundstretch.StartInfo.CreateNoWindow  = true;
            soundstretch.Start();
            soundstretch.WaitForExit();


            // wav => mp3
            if (File.Exists(outFile))
            {
                File.Delete(outFile);
            }
            using (var wav = new WaveFileReader(temp3))
                using (var mp3 = new LameMP3FileWriter(outFile, wav.WaveFormat, highQuality ? LAMEPreset.STANDARD : LAMEPreset.MEDIUM))
                    wav.CopyTo(mp3);


            // Clean up
            try
            {
                File.Delete(temp1);
                File.Delete(temp2);
                File.Delete(temp3);
            }
            catch { } // don't shit the bed if we can't delete temp files
        }
Exemple #11
0
 private static byte[] ConvertToMp3(byte[] wav)
 {
     using (var rdr = new WaveFileReader(new MemoryStream(wav)))
         using (var outMs = new MemoryStream())
             using (var wtr = new LameMP3FileWriter(outMs, rdr.WaveFormat, 24))
             {
                 rdr.CopyTo(wtr);
                 return(outMs.ToArray());
             }
 }
 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());
             }
 }
    /// <summary>
    /// Convert wav bytes to mp3 bytes
    /// derived from Gregorio Zanon's script
    /// </summary>
    /// <param name="wavFile">Wav file readed as array</param>
    /// <param name="bitRate">Mp3 bitrate. Recommend to set it to 128</param>
    /// <returns></returns>
    private static byte[] ConvertWavToMp3(byte[] wavFile, int bitRate)
    {
        var retMs = new MemoryStream();
        var ms    = new MemoryStream(wavFile);
        var rdr   = new WaveFileReader(ms);
        var wtr   = new LameMP3FileWriter(retMs, rdr.WaveFormat, bitRate);

        rdr.CopyTo(wtr);
        return(retMs.ToArray());
    }
 /// <summary>
 /// Converts the recorded WAV file to MP3
 /// </summary>
 private void ConvertWaveToMp3(string source, string destination)
 {
     using (var waveStream = new WaveFileReader(source))
         using (var fileWriter = new LameMP3FileWriter(destination, waveStream.WaveFormat, 128))
         {
             waveStream.CopyTo(fileWriter);
             waveStream.Flush();
         }
     /*Delete the temporary WAV file*/
     File.Delete(source);
 }
Exemple #15
0
 public byte[] ConvertWavToMp3(byte[] data, int br)
 {
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(data))
             using (var rdr = new WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, br))
                 {
                     rdr.CopyTo(wtr);
                     return(retMs.ToArray());
                 }
 }
Exemple #16
0
 private static byte[] ConvertWavToMp3(byte[] wavFile)
 {
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, quality: LAMEPreset.STANDARD))
                 {
                     rdr.CopyTo(wtr);
                     return(retMs.ToArray());
                 }
 }
Exemple #17
0
 public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename)
 {
     //Convert audio stream to WAV file
     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);
             }
 }
Exemple #18
0
 public static byte[] WavToMp3(byte[] wavBytes, int bitRate = 128)
 {
     using (var mp3Stream = new MemoryStream())
         using (var wavStream = new MemoryStream(wavBytes))
             using (var reader = new WaveFileReader(wavStream))
                 using (var writer = new LameMP3FileWriter(mp3Stream, reader.WaveFormat, bitRate))
                 {
                     reader.CopyTo(writer);
                     return(mp3Stream.ToArray());
                 }
 }
Exemple #19
0
 public static byte[] ConvertWavToMp3(byte[] wavFile)
 {
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 64 /*Maybe 128*/))
                 {
                     rdr.CopyTo(wtr);
                     return(retMs.ToArray());
                 }
 }
        public string Encode(string sourcePath, string destPathWithoutExtension)
        {
            var outputPath = destPathWithoutExtension + "." + FormatName;
            var reader     = new WaveFileReader(sourcePath);

            using (var writer = new LameMP3FileWriter(outputPath, reader.WaveFormat, LAMEPreset.VBR_50))
            {
                reader.CopyTo(writer);
            }
            return(outputPath);
        }
    private void WaveToMP3(string waveFileName, string mp3FileName, LAMEPreset bitRate = LAMEPreset.ABR_128)
    {
        using (var reader = new WaveFileReader(waveFileName))
            using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))
                reader.CopyTo(writer);

        GetFileKey(() =>
        {
            PutObjectWithHeader(_resultAction);
        });
    }
Exemple #22
0
 internal static byte[] ConvertToMp3(Stream wave)
 {
     wave.Position = 0;
     using (var mp3 = new MemoryStream())
         using (var reader = new WaveFileReader(wave))
             using (var writer = new LameMP3FileWriter(mp3, reader.WaveFormat, 128))
             {
                 reader.CopyTo(writer);
                 mp3.Position = 0;
                 return(mp3.ToArray());
             }
 }
Exemple #23
0
        private void WavtoMP3()
        {
            sw.Reset();
            sw.Start();
            string plik;

            do
            {
                do
                {
                    plik = textBox1.Text;
                }while (!System.IO.File.Exists(plik));
            }while (!plik.EndsWith(".wav"));
            string plikmp3  = Path.GetFileNameWithoutExtension(plik) + 2 + Path.GetExtension(plik);
            string nowyplik = Path.GetFileNameWithoutExtension(plik) + 1 + Path.GetExtension(plik);
            var    wavRdr   = new WaveFileReader(nowyplik);
            {
                using (var mp3Writer = new LameMP3FileWriter(plikmp3, wavRdr.WaveFormat, 64))
                {
                    wavRdr.CopyTo(mp3Writer);
                }
            }

            string popliku = Path.GetFileNameWithoutExtension(plikmp3) + ".mp3";

            File.Move(plikmp3, Path.ChangeExtension(plikmp3, ".mp3"));

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(popliku);
            if (fileInfo.Exists)
            {
                long   bytes     = 0;
                double kilobytes = 0;
                double megabytes = 0;

                bytes       = fileInfo.Length;
                kilobytes   = (double)bytes / 1024;
                megabytes   = kilobytes / 1024;
                y           = Math.Round(megabytes, 3);
                label3.Text = "Po konwersji: " + y + " MB";
                string format1 = fileInfo.Extension;
                label4.Text = Path.GetFileNameWithoutExtension(popliku) + "  Typ pliku: " + format1;

                z            = (100 - ((100 * y) / x));
                wynik        = Convert.ToInt32(System.Math.Floor(z));
                label11.Text = "Stopień konwersji: " + wynik + "%";
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;

            czas.Text = String.Format("{0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
            MessageBox.Show("Konwersja zakończona. Plik zapisany w: " + popliku + ".\nNaciśnij dowolny klawisz.");
            Console.In.ReadLine();
        }
Exemple #24
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;
            }
        }
Exemple #25
0
 private byte[] ConvertWavToMp3(byte[] wavFile)
 {
     using (var retMs = new MemoryStream())
         using (var ms = new MemoryStream(wavFile))
             using (var rdr = new WaveFileReader(ms))
                 using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, LAMEPreset.ABR_320))
                 {
                     rdr.CopyTo(wtr);
                     wtr.Flush();
                     return(retMs.ToArray());
                 }
 }
Exemple #26
0
        public void WavToMp3()
        {
            string inputFileName  = @"out.wav";
            string outputFileName = @"out.mp3";

            using (var reader = new WaveFileReader(inputFileName))
                using (var writer = new LameMP3FileWriter(outputFileName, reader.WaveFormat, 128))
                    reader.CopyTo(writer);
            File.Delete("out.wav");
            AddCTCSS();
            SendFile();
        }
Exemple #27
0
 public static bool ConvertWavToMP3(string wavFile, string mp3file, Action <object, long, long, bool> handler)
 {
     using (WaveFileReader rdr = new WaveFileReader(wavFile))
         using (LameMP3FileWriter wtr = new LameMP3FileWriter(mp3file, Helper.Audio.GetWavFormat(wavFile), LAMEPreset.VBR_90))
         {
             wtr.OnProgress += new NAudio.Lame.ProgressHandler(handler);
             rdr.CopyTo(wtr);
             rdr.Close();
             wtr.Close();
         }
     return(true);
 }
Exemple #28
0
        public static void ConvertWavStreamToMp3File(ref System.IO.MemoryStream ms, string savetofilename)
        {
            //rewind to beginning of stream
            ms.Seek(0, System.IO.SeekOrigin.Begin);

            using (var retMs = new System.IO.MemoryStream())
                using (var rdr = new WaveFileReader(ms))
                    using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90))
                    {
                        rdr.CopyTo(wtr);
                    }
        }
 public void Recognize(string path)
 {
     Log("Recognize: " + Path.GetFullPath(path));
     if (!File.Exists(path))
     {
         return;
     }
     using (var reader = new WaveFileReader(path)) {
         var tmp = buffer.Position;
         reader.CopyTo(buffer);
         buffer.Position = tmp;
     }
 }
Exemple #30
0
        /// <summary>
        /// Concat a list of WAV in a MP3 file
        /// </summary>
        /// <param name="inputFiles">List of input WAV files paths</param>
        /// <param name="outputFile">Output MP3 file path</param>
        /// <param name="id3Tag">MP3 tags</param>
        public static void WavToMp3(List <string> inputFiles, string outputFile, ID3TagData id3Tag)
        {
            var writer = new LameMP3FileWriter(outputFile, TempWaveFormat, ExportQuality, id3Tag);

            foreach (var inputFile in inputFiles)
            {
                var reader = new WaveFileReader(inputFile);
                reader.CopyTo(writer);
                reader.Close();
            }
            writer.Flush();
            writer.Close();
        }