Esempio n. 1
0
        public Task Convert(string Inputfile, string OutputFile)
        {
            StopWatch w = new StopWatch();

            if (!Initialized)
            {
                Initialized = true;
                MediaFoundationApi.Startup();
            }
            return(new Task(delegate()
            {
                FileInfo inf = new FileInfo(OutputFile);
                AudioFileReader FileR = new AudioFileReader(Inputfile);
                string l = inf.Extension.ToLower();
                if (l.EndsWith("mp3"))
                {
                    MediaFoundationEncoder.EncodeToMp3(FileR, OutputFile, Bitrate);
                }
                else if (l.EndsWith("wma"))
                {
                    MediaFoundationEncoder.EncodeToWma(FileR, OutputFile, Bitrate);
                }
                else if (l.EndsWith("aac"))
                {
                    MediaFoundationEncoder.EncodeToAac(FileR, OutputFile, Bitrate);
                }
                else
                {
                    throw new NotSupportedException("Format not supported");
                }
                w.PrintDur("MediaProvider");
            }));
        }
Esempio n. 2
0
        private void convertButton_Click(object sender, EventArgs e)
        {
            MediaFoundationReader foundationReader = new MediaFoundationReader(OFD.FileName);
            SaveFileDialog        SFD = new SaveFileDialog();

            SFD.Title = "Save here your file";
            if (mp3RadioButton.Checked)
            {
                SFD.Filter = "MP3|*.mp3";
                SFD.ShowDialog();
                MediaFoundationEncoder.EncodeToMp3(foundationReader, SFD.FileName);
            }
            if (aacRadioButton.Checked)
            {
                SFD.Filter = "AAC|*.aac";
                SFD.ShowDialog();
                MediaFoundationEncoder.EncodeToAac(foundationReader, SFD.FileName);
            }
            if (wmaRadioButton.Checked)
            {
                SFD.Filter = "WMA|*.wma";
                SFD.ShowDialog();
                MediaFoundationEncoder.EncodeToWma(foundationReader, SFD.FileName);
            }
        }
Esempio n. 3
0
        private void Convert()
        {
            var reader = new MediaFoundationReader(fileSource.FullName);

            switch (type)
            {
            case ConvertType.ToMP3:
                MediaFoundationEncoder.EncodeToMp3(reader, desPath);
                break;

            case ConvertType.ToAAC:
                MediaFoundationEncoder.EncodeToAac(reader, desPath);
                break;

            case ConvertType.ToWMA:
                MediaFoundationEncoder.EncodeToWma(reader, desPath);
                break;

            case ConvertType.ToWAV:
                WaveFileWriter.CreateWaveFile(desPath, reader);
                break;

            default:
                break;
            }
            MsgBox.Show("Convert Completed!!!", "Notification", MsgBox.Buttons.OK);
        }
Esempio n. 4
0
 public static void WavToMp4(string relativePath)
 {
     using (var reader = new MediaFoundationReader($"{BotTools.BasePath}\\{relativePath}.wav"))
     {
         MediaFoundationEncoder.EncodeToAac(reader, $"{BotTools.BasePath}\\{relativePath}.mp4");
     }
 }
Esempio n. 5
0
        public override async void StartDownload()
        {
            await Task.Run(() =>
            {
                OnDownloadItemDownloadStarted(null);

                var oldExtension = Path.GetExtension(CurrentPath)?.ToLower();
                var newExtension = Path.GetExtension(NewPath)?.ToLower();

                if ((oldExtension == ".m4a") && (newExtension == ".mp3"))
                {
                    try
                    {
                        OnDownloadItemConvertionStarted(null);

                        using (var reader = new MediaFoundationReader(CurrentPath))
                        {
                            MediaFoundationEncoder.EncodeToMp3(reader, NewPath);
                        }

                        File.Delete(CurrentPath);

                        OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(false));
                    }
                    catch (Exception ex)
                    {
                        OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, ex));
                    }
                }
                else if ((oldExtension == ".mp3") && (newExtension == ".m4a"))
                {
                    try
                    {
                        OnDownloadItemConvertionStarted(null);

                        using (var reader = new MediaFoundationReader(CurrentPath))
                        {
                            MediaFoundationEncoder.EncodeToAac(reader, NewPath);
                        }

                        File.Delete(CurrentPath);

                        OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(false));
                    }
                    catch (Exception ex)
                    {
                        OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, ex));
                    }
                }
                else
                {
                    OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true,
                                                                                   new InvalidOperationException("No supported extension")));
                }
            });
        }
Esempio n. 6
0
 public void Encode(Stream source, string outputPath, SongTags tags, byte[] reusedBuffer)
 {
     using (var reader = new WaveFileReader(source))
     {
         MediaFoundationEncoder.EncodeToAac(
             reader,
             outputPath
             );
     }
 }
Esempio n. 7
0
        private void WAVtoMP4()
        {
            sw.Reset();
            sw.Start();
            string plik;

            do
            {
                do
                {
                    plik = textBox1.Text;
                }while (!System.IO.File.Exists(plik));
            }while (!plik.EndsWith(".wav"));
            string plikwav     = plik.Replace(".wav", ".mp4");
            string pliksciezka = plikwav;

            int    index    = plikwav.LastIndexOf("\\");
            string nazwawav = plikwav.Substring(index + 1, plikwav.Length - index - 1);

            index = plik.LastIndexOf("\\");
            string nazwamp3 = plik.Substring(index + 1, plik.Length - index - 1);

            using (var reader = new MediaFoundationReader(textBox1.Text))
            {
                MediaFoundationEncoder.EncodeToAac(reader, plikwav);
            }

            string path1 = Path.GetFileName(plikwav);

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

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

                z            = 100 - (y / x) * 100;
                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: " + plikwav + ".\nNaciśnij dowolny klawisz.");
            Console.In.ReadLine();
        }
Esempio n. 8
0
        /// <summary>
        /// The BackgroundWorker_DoWork.
        /// </summary>
        /// <param name="sender">The sender<see cref="object"/>.</param>
        /// <param name="e">The e<see cref="DoWorkEventArgs"/>.</param>
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            progress = 0.0;

            // loop through selected ACM items
            foreach (int index in chkListBox.CheckedIndices)
            {
                if (this.IsDisposed)
                {
                    break;
                }

                ACM acm = acms[index];
                acm.WaveStream.Position = 0;                 // important! - always read stream from position 0.

                WaveFormat outWaveFormat = new WaveFormat(); // output format: 16bit, 44.1 kHz
                // Input is 16bit, 22050 Hz
                WaveFormatConversionStream waveFormatConversionStream = new WaveFormatConversionStream(outWaveFormat, acm.WaveStream);

                int    li      = acm.Tag.LastIndexOf('.'); // last index of dot; point is to remove extension to add the new one
                string outFile = outDir + Path.DirectorySeparatorChar + acm.Tag.Substring(0, li + 1) + audioFormat.ToString().ToLower();
                switch (audioFormat)
                {
                case AudioFormat.AAC:
                    MediaFoundationApi.Startup();
                    MediaFoundationEncoder.EncodeToAac(waveFormatConversionStream, outFile);
                    MediaFoundationApi.Shutdown();
                    break;

                case AudioFormat.MP3:
                    MediaFoundationApi.Startup();
                    MediaFoundationEncoder.EncodeToMp3(waveFormatConversionStream, outFile);
                    MediaFoundationApi.Shutdown();
                    break;

                case AudioFormat.WAV:
                    using (waveFormatConversionStream)
                    {
                        WaveFileWriter.CreateWaveFile(outFile, waveFormatConversionStream);
                    }
                    break;
                }
                progress += 100.0 / (double)chkListBox.CheckedItems.Count;
                backgroundWorker.ReportProgress((int)progress);
            }
            progress = 100.0;
        }
Esempio n. 9
0
        /// <summary>
        /// Transcodes the source audio to the target format and quality.
        /// </summary>
        /// <param name="formatType">Format to convert this audio to.</param>
        /// <param name="quality">Quality of the processed output audio. For streaming formats, it can be one of the following: Low (96 kbps), Medium (128 kbps), Best (192 kbps).  For WAV formats, it can be one of the following: Low (11kHz ADPCM), Medium (22kHz ADPCM), Best (44kHz PCM)</param>
        /// <param name="targetFileName">Name of the file containing the processed source audio. Must be null for Wav and Adpcm. Must not be null for streaming compressed formats.</param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("AudioContent");
            }

            switch (formatType)
            {
            case ConversionFormat.Adpcm:
                ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                break;

            case ConversionFormat.Pcm:
                ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                break;

            case ConversionFormat.WindowsMedia:
#if WINDOWS
                reader.Position = 0;
                MediaFoundationEncoder.EncodeToWma(reader, targetFileName, QualityToBitRate(quality));
                break;
#else
                throw new NotSupportedException("WindowsMedia encoding supported on Windows only");
#endif

            case ConversionFormat.Xma:
                throw new NotSupportedException("XMA is not a supported encoding format. It is specific to the Xbox 360.");

            case ConversionFormat.ImaAdpcm:
                ConvertWav(new ImaAdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount, 4));
                break;

            case ConversionFormat.Aac:
#if WINDOWS
                reader.Position = 0;
                MediaFoundationEncoder.EncodeToAac(reader, targetFileName, QualityToBitRate(quality));
                break;
#else
                throw new NotImplementedException();
#endif

            case ConversionFormat.Vorbis:
                throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
Esempio n. 10
0
        public void Convert(ICollection <InputFileItem> fileItems)
        {
            _tokenSource = new CancellationTokenSource();
            Task.Run(() =>
            {
                try
                {
                    OnConvert?.Invoke(this, new ConvertEventArgs(ConvertEventType.BeginConvert, $"{Properties.Resources.Convert_Start} {fileItems.Count()} {Properties.Resources.files}"));
                    foreach (var item in fileItems)
                    {
                        if (_tokenSource.IsCancellationRequested)
                        {
                            _tokenSource.Token.ThrowIfCancellationRequested();
                        }

                        if (!item.Path.EndsWith("m4a") && !item.Path.EndsWith(".m4b"))
                        {
                            OnConvert?.Invoke(this, new ConvertEventArgs(ConvertEventType.ConvertToAAC, $"{Properties.Resources.Converting}: {item.FileName}"));
                            using (var filestream = new MediaFoundationReader(item.Path))
                            {
                                item.WorkingPath = Path.GetTempFileName();
                                MediaFoundationEncoder.EncodeToAac(filestream, item.WorkingPath);
                            }
                        }
                    }
                    OnConvert?.Invoke(this, new ConvertEventArgs(ConvertEventType.EndConvert));
                }
                catch (OperationCanceledException oe)
                {
                    OnConvert?.Invoke(this, new ConvertEventArgs(ConvertEventType.Cancelled, oe.Message));
                }
                catch (Exception e)
                {
                    OnConvert?.Invoke(this, new ConvertEventArgs(ConvertEventType.Error, e.Message));
                }
                finally
                {
                    foreach (var item in fileItems)
                    {
                        File.Delete(item.WorkingPath);
                    }
                }
            }, _tokenSource.Token);
        }
Esempio n. 11
0
        private void Save()
        {
            if (reader == null)
            {
                return;
            }
            if (player.PlaybackState != PlaybackState.Stopped)
            {
                player.Stop();
            }
            reader.CurrentTime = TimeSpan.Zero;
            var duration = barEditor.CutStopTime - barEditor.CutStartTime;
            var fadeIn   = rdbFadeIn.Checked ? TimeSpan.FromSeconds(FADESECONDS) : TimeSpan.Zero;
            var fadeOut  = rdbFadeOut.Checked ? TimeSpan.FromSeconds(FADESECONDS) : TimeSpan.Zero;
            var skip     = barEditor.CutStartTime;
            var volume   = Convert.ToBoolean(btnVolumeBoost.Tag) ? 1F : 0.5F;
            var temp     = Path.Combine(Path.GetTempPath(), OUTPUTFILENAME);

            if (File.Exists(temp))
            {
                File.Delete(temp);
            }
            var resampler = new MediaFoundationResampler(GetProvider(reader, duration, fadeIn, fadeOut, skip, volume).ToWaveProvider(), 48000);

            MediaFoundationEncoder.EncodeToAac(resampler, temp, 0);
            reader.Close();
            reader.Dispose();
            var folder = Path.GetDirectoryName(reader.FileName);
            var name   = Path.GetFileNameWithoutExtension(reader.FileName);

            if (File.Exists(name + RINGTONEEXTENSION))
            {
                var i = 1;
                while (File.Exists(name + i + RINGTONEEXTENSION))
                {
                    i++;
                }
                name += i;
            }
            var result = Path.Combine(folder, name + RINGTONEEXTENSION);

            File.Move(temp, result);
        }
Esempio n. 12
0
 static void Main(string[] args)
 {
     // convert source audio to AAC
     // create media foundation reader to read the source (can be any supported format, mp3, wav, ...)
     using (MediaFoundationReader reader = new MediaFoundationReader(@"d:\source.mp3"))
     {
         MediaFoundationEncoder.EncodeToAac(reader, @"D:\test.mp4");
     }
     // convert "back" to WAV
     // create media foundation reader to read the AAC encoded file
     using (MediaFoundationReader reader = new MediaFoundationReader(@"D:\test.mp4"))
         // resample the file to PCM with same sample rate, channels and bits per sample
         using (ResamplerDmoStream resampledReader = new ResamplerDmoStream(reader,
                                                                            new WaveFormat(reader.WaveFormat.SampleRate, reader.WaveFormat.BitsPerSample, reader.WaveFormat.Channels)))
             // create WAVe file
             using (WaveFileWriter waveWriter = new WaveFileWriter(@"d:\test.wav", resampledReader.WaveFormat))
             {
                 // copy samples
                 resampledReader.CopyTo(waveWriter);
             }
 }
Esempio n. 13
0
 static void ConvertToAAC(string input, string output)
 {
     using (var reader = new MediaFoundationReader(input))
         MediaFoundationEncoder.EncodeToAac(reader, output);
 }
Esempio n. 14
0
 // Convert MP3 file to M4A using NAudio classes only
 public static void MP3ToM4A(string mp3FileName, string m4aFileName)
 {
     using (var reader = new Mp3FileReader(mp3FileName))
         MediaFoundationEncoder.EncodeToAac(reader, m4aFileName);
 }
Esempio n. 15
0
        public static FileInfo Convert(DirectoryInfo folder)
        {
            var fileItems = folder.GetFiles("*.mp3").Select(s => new FileItem(s.FullName)).ToArray();

            if (fileItems?.Any() == false)
            {
                return(null);
            }


            var mp3Merged = Path.GetTempFileName();
            var aacMerged = mp3Merged + ".m4a";

            try
            {
                using (var str = new FileStream(mp3Merged, FileMode.OpenOrCreate))
                {
                    foreach (var file in fileItems)
                    {
                        Mp3FileReader reader = new Mp3FileReader(file.Path);
                        if ((str.Position == 0) && (reader.Id3v2Tag != null))
                        {
                            str.Write(reader.Id3v2Tag.RawData, 0, reader.Id3v2Tag.RawData.Length);
                        }
                        Mp3Frame frame;
                        while ((frame = reader.ReadNextFrame()) != null)
                        {
                            str.Write(frame.RawData, 0, frame.RawData.Length);
                        }
                    }
                }

                using (var filestream = new MediaFoundationReader(mp3Merged))
                {
                    MediaFoundationEncoder.EncodeToAac(filestream, aacMerged);
                }


                var first = fileItems.First().TrackInfo;

                var finallyMerged = $"{folder.FullName}{first.Artist} - {first.Album}.m4b";

                foreach (var c in Path.GetInvalidFileNameChars())
                {
                    finallyMerged = finallyMerged.Replace(c, '_');
                }

                File.Move(aacMerged, finallyMerged);
                Settings.MP4_createNeroChapters      = true;
                Settings.MP4_createQuicktimeChapters = true;

                var aacTrack = new Track(finallyMerged);



                aacTrack.Album       = first.Album;
                aacTrack.AlbumArtist = first.AlbumArtist;
                aacTrack.Artist      = first.Artist;
                aacTrack.Date        = first.Date;
                aacTrack.Title       = first.Album;
                foreach (var pToken in first.PictureTokens)
                {
                    aacTrack.PictureTokens.Add(pToken);
                }

                foreach (var picutre in first.EmbeddedPictures)
                {
                    aacTrack.EmbeddedPictures.Add(picutre);
                }

                var timemarker = new TimeSpan();

                foreach (var fileItem in fileItems)
                {
                    var chapter = new ChapterInfo
                    {
                        Title       = fileItem.TrackInfo.Title,
                        StartTime   = (uint)timemarker.TotalMilliseconds,
                        StartOffset = (uint)timemarker.TotalMilliseconds
                    };
                    timemarker       += TimeSpan.FromMilliseconds(fileItem.TrackInfo.DurationMs);
                    chapter.EndTime   = (uint)timemarker.TotalMilliseconds;
                    chapter.EndOffset = (uint)timemarker.TotalMilliseconds;
                    aacTrack.Chapters.Add(chapter);
                }

                aacTrack.Save();
                return(new FileInfo(finallyMerged));
            }
            finally
            {
                File.Delete(mp3Merged);
            }
        }