/// <summary>
        /// Converts WAV content to MP3.
        /// </summary>
        /// <param name="wavStream"></param>
        /// <param name="mp3ResultFile"></param>
        public static void SaveWavToMp3File(this Stream wavStream, string mp3ResultFile)
        {
            MediaFoundationApi.Startup();
            try
            {
                using var reader = new WaveFileReader(inputStream: wavStream);

                //MediaFoundationEncoder.EncodeToMp3(reader, outputFile: mp3ResultFile, desiredBitRate: desiredMP3bitRate);

                var mediaType = MediaFoundationEncoder.SelectMediaType(
                    AudioSubtypes.MFAudioFormat_MP3,
                    new WaveFormat(sampleRate: audio_sample_rate, channels: audio_channels),
                    desiredBitRate: desiredMP3bitRate);
                if (mediaType == null)
                {
                    throw new NotSupportedException();
                }
                using var enc = new MediaFoundationEncoder(mediaType);
                enc.Encode(outputFile: mp3ResultFile, reader);
            }
            finally
            {
                MediaFoundationApi.Shutdown();
            }
        }
Beispiel #2
0
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter      = "WAV Files (*.wav)|*.wav|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var inputFileName  = openFileDialog.FileName;
                var outputFileName = inputFileName.Substring(0, inputFileName.Length - 3) + "mp3";

                var mediaType = MediaFoundationEncoder.SelectMediaType(
                    AudioSubtypes.MFAudioFormat_MP3,
                    new WaveFormat(44100, 1),
                    0);

                using (var reader = new MediaFoundationReader(inputFileName))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(outputFileName, reader);
                    }
                }
            }

            MessageBox.Show("操作成功");
        }
        public bool ExportAudio(string changedSoundName)
        {
            try
            {
                if (soundFilePath != null && streamProcessor != null)
                {
                    //MediaType mediaType;
                    switch (nowParseSoundFormat)
                    {
                    case SupportedAudioFormat.MP3:
                        var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, new WaveFormat(44100, 2), 256000);
                        using (var reader = new MediaFoundationReader(soundFilePath))     //这里暂时没用,是导入已存在的音频文件
                        {
                            using (var encoder = new MediaFoundationEncoder(mediaType))
                            {
                                encoder.Encode(changedSoundName, streamProcessor);    //直接用被soundtouch处理的音频wav
                            }
                        }
                        return(true);

                    case SupportedAudioFormat.OGG:
                        WaveFileWriter.CreateWaveFile(changedSoundName.Replace(".ogg", ".wav"), streamProcessor);

                        using (Sox sox = new Sox(@"SOX\sox.exe"))
                        {
                            sox.OnProgress        += sox_OnProgress;
                            sox.Output.SampleRate  = 44100;
                            sox.Output.Compression = 7;    //压缩率1-10
                            sox.Process(changedSoundName.Replace(".ogg", ".wav"), changedSoundName);
                        }
                        File.Delete(changedSoundName.Replace(".ogg", ".wav"));
                        return(true);

                    default:
                        return(false);
                    }

                    //var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, new WaveFormat(44100, 2), 256000);
                    //using (var reader = new MediaFoundationReader(soundFilePath)) //这里暂时没用,是导入已存在的音频文件
                    //{
                    //    using (var encoder = new MediaFoundationEncoder(mediaType))
                    //    {

                    //        encoder.Encode(changedSoundName, streamProcessor);//直接用被soundtouch处理的音频wav
                    //    }
                    //}
                    //return true;
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                //return false;
                throw;
            }
        }
Beispiel #4
0
        /// <summary>
        /// 将wav文件转换为mp3文件
        /// </summary>
        /// <param name="wavFile">wav文件路径</param>
        /// <param name="mp3File">mp3文件路径</param>
        public static void WAVtoMP3(string wavFile, string mp3File)
        {
            var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, new WaveFormat(44100, 1), 0);

            using (var reader = new MediaFoundationReader(wavFile))
            {
                using (var encoder = new MediaFoundationEncoder(mediaType))
                {
                    encoder.Encode(mp3File, reader);
                }
            }
        }
Beispiel #5
0
        private static void WavToMp3(string WavFile, string Mp3File)
        {
            NAudio.MediaFoundation.MediaFoundationApi.Startup();
            var mediaType = MediaFoundationEncoder.SelectMediaType(NAudio.MediaFoundation.AudioSubtypes.MFAudioFormat_WMAudioV8, new WaveFormat(16000, 1), 16000);

            if (mediaType != null)
            {
                using (var wavreader = new WaveFileReader(WavFile))
                {
                    MediaFoundationEncoder.EncodeToMp3(wavreader, Mp3File, 48000);
                }
            }
            NAudio.MediaFoundation.MediaFoundationApi.Shutdown();
        }
 /// <summary>
 /// Converts a single wav file to a single mp3 file.
 /// </summary>
 public void startConvert()
 {
     if (File.Exists(infile))
     {
         WaveFileReader reader    = new WaveFileReader(infile);
         MediaType      mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, reader.WaveFormat, 256000);
         using (MediaFoundationEncoder encoder = new MediaFoundationEncoder(mediaType))
         {
             encoder.Encode(outfile, reader);
         }
         reader.Close();
         reader.Dispose();
     }
 }
Beispiel #7
0
        public static bool WriteMp3(string filename, WaveFormat format)
        {
            var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, format, 192000);

            if (mediaType != null)
            {
                using (var reader = new WaveFileReader(Path.Combine(Path.GetTempPath(), "recording.wav")))
                {
                    MediaFoundationEncoder.EncodeToMp3(reader, filename, 192000);
                    return(true);
                }
            }
            return(false);
        }
Beispiel #8
0
        private void CopyWavToMp3(string wavFileName)
        {
            Task.Run(() =>
            {
                try
                {
                    var reader      = new MediaFoundationReader(wavFileName);
                    var mp3         = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, reader.WaveFormat, 64000);
                    var mp3FileName = Path.Combine(Path.GetDirectoryName(wavFileName), $"{Path.GetFileNameWithoutExtension(wavFileName)}.mp3");

                    using (var converter = new MediaFoundationEncoder(mp3))
                    {
                        converter.Encode(mp3FileName, reader);
                    }
                    File.Delete(wavFileName);
                    LOG.WriteLine(LLV.INF, $"Saved as {Path.GetFileName(mp3FileName)} at {Path.GetDirectoryName(mp3FileName)}");
                }
                catch (Exception ex)
                {
                    LOG.WriteLine(LLV.WAR, $"Saved as {wavFileName}");
                }
            });
        }
Beispiel #9
0
        // download dialog
        private async void btnDownload_Click(object sender, EventArgs e)
        {
            // Remove Illegal Path Characters
            string fileName = RemoveIllegalPathCharacters(txtBoxVidName.Text);

            // clear the picture box
            Thumbnail.Image = null;

            // clear pasted text
            TxtUrl.Text = "";

            // make sure the file isn't the same as ones being downloading or get an IO exception
            for (int i = 0; i < listView.Items.Count; i++)
            {
                // checking if the downloading files isn't the one trying to be downloaded
                if (listView.Items[i].SubItems[(int)subItems.fileName].Text == fileName)
                {
                    // disable and clear the ui and tell the user it's already being downloading
                    toggleThings(false);
                    Thumbnail.Image    = null;
                    txtLoading.Text    = "Already added";
                    txtLoading.Visible = true;
                    return;
                }
            }

            // if the user picked to download audio or video
            if (comBoxVideo.SelectedIndex == -1)
            {
                // copy the cut values off the UI thread
                int first = barFirst.Value;
                int last  = barLast.Maximum - barLast.Value;

                // reset the video settings in the UI
                toggleThings(false);
                Refresh();

                try
                {
                    // download the auido from url
                    using (var reader = new MediaFoundationReader(audioUrl))
                    {
                        // set up the encoder for mp3 file formate
                        var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, reader.WaveFormat, Bitrate);
                        if (mediaType == null)
                        {
                            throw new InvalidOperationException("No suitable MP3 encoders available");
                        }
                        var audio = new CustomMediaFoundationEncoder(mediaType)
                        {
                            // add all the nessary varables to the custom class
                            Item    = LvAddItem(ref listView, fileName, out ProgressBar progbar),
                            ProgBar = progbar,
                            Index   = listView.Items.Count - 1
                        };

                        audio.LoadProgressChanged += encoder_LoadProgressChanged;
                        audio.LoadComplete        += encoder_LoadComplete;

                        // encode it to mp3
                        await Task.Run(() => audio.Encode($"{FilePath}{fileName}.mp3", reader, first, last));

                        void encoder_LoadProgressChanged(object o, LoadProgressChangedEventArgs ev)
                        {
                            // set current encoder
                            var encoder = o as CustomMediaFoundationEncoder;

                            // Running on the UI thread
                            listView.Invoke((MethodInvoker) delegate
                            {
                                // update the bytes received in the listView
                                encoder.Item.SubItems[(int)subItems.Total].Text =
                                    $"{ev.TimeEncoded:mm\\:ss} / {ev.TotalTimeToEncode:mm\\:ss}";
                            });

                            // Running on the UI thread
                            encoder.ProgBar.Invoke((MethodInvoker) delegate
                            {
                                // set the progress on the progress bar
                                encoder.ProgBar.Value = ev.ProgressPercentage;

                                // checks if the listitem has moved down
                                if (encoder.Item.Index != encoder.Index)
                                {
                                    encoder.Index = encoder.Item.Index;

                                    // move the progress bar down one
                                    encoder.ProgBar.Top -= 18;
                                }
                            });
                        }

                        void encoder_LoadComplete(object o, EventArgs ev)
                        {
                            // puts the source url in the .mp3 meta data in the comment section
                            TagLib.File f = TagLib.File.Create($"{FilePath}{fileName}.mp3");
                            f.Tag.Comment = $"www.youtube.com/watch?v={id}";
                            f.Save();

                            // set current encoder
                            var encoder = o as CustomMediaFoundationEncoder;

                            encoder.LoadProgressChanged -= encoder_LoadProgressChanged;
                            encoder.LoadComplete        -= encoder_LoadComplete;

                            // Running on the UI thread, remove the progress bar
                            encoder.ProgBar.Invoke((MethodInvoker) delegate {
                                encoder.ProgBar.Dispose();
                            });

                            // Running on the UI thread, remove the listViewItem
                            listView.Invoke((MethodInvoker) delegate {
                                encoder.Item.Remove();
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    // if something messes up tell the user
                    txtLoading.Text    = ex.Message;
                    txtLoading.Visible = true;
                }
            }
            else
            {
                // get the video codec
                string item  = comBoxVideo.Items[comBoxVideo.SelectedIndex] as string;
                string codec = item.Split(' ')[2];

                // getting the download url
                string url = videoUrls[comBoxVideo.SelectedIndex];

                // reset the video settings in the UI
                toggleThings(false);
                Refresh();

                // download the video from url
                using (CustomWebClient web = new CustomWebClient())
                {
                    // adds a download item to the listview
                    web.Item = LvAddItem(ref listView, fileName, out ProgressBar probar);

                    // add the progress bar
                    web.ProgBar = probar;

                    // the position in the listViewItem to measure changes
                    web.Index = listView.Items.Count - 1;

                    // add events
                    web.DownloadProgressChanged += web_DownloadProgressChanged;
                    web.DownloadFileCompleted   += web_DownloadFileCompleted;

                    // download the video file
                    await web.DownloadFileTaskAsync(url, FilePath + fileName + codec);

                    // displaying the download progress
                    void web_DownloadProgressChanged(object o, DownloadProgressChangedEventArgs ev)
                    {
                        // set current webclient
                        var customWebClient = o as CustomWebClient;

                        // set the progress on the progress bar
                        customWebClient.ProgBar.Value = ev.ProgressPercentage;

                        // checks if the listitem has moved down
                        if (customWebClient.Item.Index != customWebClient.Index)
                        {
                            customWebClient.Index = customWebClient.Item.Index;

                            // move the progress bar down one
                            customWebClient.ProgBar.Top -= 18;
                        }

                        // update the bytes received in the listViewItem
                        customWebClient.Item.SubItems[(int)subItems.Total].Text =
                            $"{ev.BytesReceived / 1024f / 1042f:00.00} / {ev.TotalBytesToReceive / 1024f / 1024f:00.00} MB";
                    }

                    // download complete
                    void web_DownloadFileCompleted(object o, AsyncCompletedEventArgs ev)
                    {
                        // set current webclient
                        var customWebClient = o as CustomWebClient;

                        // remove the progress bar
                        customWebClient.ProgBar.Dispose();

                        // removes downloaded element
                        customWebClient.Item.Remove();

                        // remove events
                        customWebClient.DownloadProgressChanged -= web_DownloadProgressChanged;
                        customWebClient.DownloadFileCompleted   -= web_DownloadFileCompleted;
                    }
                }
            }
        }
Beispiel #10
0
 protected override MediaType GetMediaType(WaveFormat waveFormat) => MediaFoundationEncoder.SelectMediaType(
     AudioSubtypes.MFAudioFormat_MP3,
     waveFormat,
     128000);
        public static void ConvertWavToMp3_POC(string wav, string mp3) // NOT TESTED  see more at     http://mark-dot-net.blogspot.ca/2015/02/how-to-encode-mp3s-with-naudio.html
        {
            var wav2 = @"D:\Users\alex\Videos\0Pod\Cuts\BPr-6659,`Hacking Addiction with Dr. Mark – #351\[012].--- 65 ---.wav";

            try
            {
                var mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_WMAudioV8, new WaveFormat(16000, 1), 16000); if (mediaType != null)
                {
                    Debug.WriteLine(" we can encode");
                }

                mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, new WaveFormat(44100, 1), 0); if (mediaType != null)
                {
                    Debug.WriteLine(" we can encode");
                }
                mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, new WaveFormat(352000, 1), 0); if (mediaType != null)
                {
                    Debug.WriteLine(" we can encode");
                }

                var incoming = new WaveFileReader(wav);
                var outgoing = new WaveFileReader(wav2);

                var mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(16000, 1));
                Debug.WriteLine(mixer.WaveFormat.ToString());

                // add the inputs - they will automatically be turned into ISampleProviders
                mixer.AddMixerInput(incoming);
                mixer.AddMixerInput(outgoing);

                //var truncateAudio = true;        // optionally truncate to 30 second for unlicensed users
                var truncated = //truncateAudio ? new OffsetSampleProvider(mixer) { Take = TimeSpan.FromSeconds(30) } :
                                (ISampleProvider)mixer;

                // go back down to 16 bit PCM
                var converted16Bit = new SampleToWaveProvider16(truncated);

                // now for MP3, we need to upsample to 44.1kHz. Use MediaFoundationResampler
                using (var resampled = new MediaFoundationResampler(converted16Bit, new WaveFormat(44100, 1)))
                {
                    var desiredBitRate = 0; // ask for lowest available bitrate
                    MediaFoundationEncoder.EncodeToMp3(resampled, "mixed.mp3", desiredBitRate);
                }



                var myWaveProvider = (IWaveProvider) new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(16000, 1));

                using (var enc = new MediaFoundationEncoder(mediaType))
                {
                    enc.Encode("output.wma", myWaveProvider);
                }

                using (var reader = new WaveFileReader(wav))
                {
                    MediaFoundationEncoder.EncodeToMp3(reader, mp3, 48000);
                }
            }
            catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, System.Reflection.MethodInfo.GetCurrentMethod().Name); if (System.Diagnostics.Debugger.IsAttached)
                                   {
                                       System.Diagnostics.Debugger.Break();
                                   }
                                   throw; }
        }
Beispiel #12
0
 /// <summary>
 /// Determines whether encoding to MP3 is possible based on the current environment.
 /// </summary>
 /// <returns><c>true</c> when encoding is possible; otherwise <c>false</c>.</returns>
 public bool CanEncodeToMP3()
 => MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, Constants.DefaultWaveFormat, Constants.DesiredBitRate) != null;