Ejemplo n.º 1
0
        public override async Task <CommandResult> RunVoiceCommand(string[] args, CommandContext context, ConnectionModel connection)
        {
            using (MediaFoundationReader reader = new MediaFoundationReader(connection.NowPlaying.FilePath))
            {
                string file = Path.Combine(Path.GetTempPath(), $"{connection.NowPlaying}.mp3");
                if (File.Exists(file))
                {
                    await context.Channel.SendFileAsync(file);
                }
                else
                {
                    MediaFoundationEncoder.EncodeToMp3(reader, file);
                    using (TagLib.File tag = TagLib.File.Create(file))
                    {
                        tag.Tag.Title        = connection.NowPlaying.Title;
                        tag.Tag.Album        = connection.NowPlaying.Album;
                        tag.Tag.AlbumArtists = new string[] { connection.NowPlaying.Artist };
                        tag.Tag.Pictures     = new TagLib.IPicture[] { new TagLib.Picture(connection.NowPlaying.ThumbnailPath) };
                        tag.Save();
                    }

                    await context.Channel.SendFileAsync(file);
                }
            }

            return(CommandResult.Empty);
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
        public static void CreateMashup(string to, params string[] files)
        {
            if (files.Length < 2)
            {
                throw new Exception("Not enough files selected!");
            }

            var internalFormat = WaveFormat.CreateIeeeFloatWaveFormat(16000, 1);
            var toFormat       = WaveFormat.CreateIeeeFloatWaveFormat(44100, 1);
            var mixer          = new MixingSampleProvider(internalFormat);

            var readers             = files.Select(path => new Mp3FileReader(path)).ToList();
            var waveStreams         = readers.Select(WaveFormatConversionStream.CreatePcmStream).ToList();
            var resampledEnumerable = waveStreams.Select(stream => new MediaFoundationResampler(stream, internalFormat)).ToList();

            foreach (var resampled in resampledEnumerable)
            {
                mixer.AddMixerInput(resampled);
            }

            var waveProvider = new SampleToWaveProvider(mixer);

            using (var resampler = new MediaFoundationResampler(waveProvider, toFormat))
            {
                MediaFoundationEncoder.EncodeToMp3(resampler, to);
            }

            resampledEnumerable.Dispose();
            waveStreams.Dispose();
            readers.Dispose();
        }
Ejemplo n.º 4
0
        public static bool ConvertM4AToMp3(byte[] m4AFile, string directory, ref Track song)
        //requires windows 8 or higher
        {
            var tempFile = Path.Combine(directory, "tempdata" + _uniqueTempFileCounter + ".m4a");

            //

            try
            {
                _uniqueTempFileCounter += 1;
                File.WriteAllBytes(tempFile, m4AFile);
                song.LocalPath += ".mp3";                                //conversion wil result in an mp3
                using (var reader = new MediaFoundationReader(tempFile)) //this reader supports: MP3, AAC and WAV
                {
                    var aaCtype  = AudioSubtypes.MFAudioFormat_AAC;
                    var bitrates = MediaFoundationEncoder.GetEncodeBitrates(aaCtype, reader.WaveFormat.SampleRate,
                                                                            reader.WaveFormat.Channels);
                    MediaFoundationEncoder.EncodeToMp3(reader, song.LocalPath, bitrates[bitrates.GetUpperBound(0)]);
                }
                File.Delete(tempFile);
                return(true);
            }
            catch (Exception)
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                return(false);
            }
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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");
            }));
        }
Ejemplo n.º 7
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            string         soundLink = GetGUISoundLink();
            SaveFileDialog dialog    = new SaveFileDialog();

            dialog.Filter   = "MP3 File (*.mp3)|*.mp3";
            dialog.FileName = "tts.mp3";
            var s = dialog.ShowDialog();

            if (s == DialogResult.OK)
            {
                if (!Program.bOldWindows)
                {
                    using (var mf = new MediaFoundationReader(soundLink))
                    {
                        PitchProvider             = new SmbPitchShiftingSampleProvider(mf.ToSampleProvider().ToMono());
                        PitchProvider.PitchFactor = Pitch;
                        MediaFoundationEncoder.EncodeToMp3(PitchProvider.ToWaveProvider(), dialog.FileName, 48000);
                        MessageBox.Show(downloaded);
                    }
                }
                else
                {
                    using (var wc = new WebClient())
                    {
                        wc.DownloadFile(soundLink, dialog.FileName);
                        MessageBox.Show(downloaded);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void DetectBPM(string[] files)
        {
            //Detected und setzt im ID3-Tag die BPM der einzelne files
            string filename;
            double bpm;

            foreach (var file in Directory.EnumerateFiles(_dirConverted))
            {
                var fileinfo = new FileInfo(file);
                filename = fileinfo.Name;
                var outfile = _dirConverted + filename + ".mp3";
                //BPMDetector zusätzliches plugin zur Naudio Library zum messen der BPM
                BPMDetector bPMDetector = new BPMDetector(file);
                bpm = bPMDetector.getBPM();
                //Konvertiert die Dateien zu MP3 um den Tag setzten zu können
                using (var reader = new MediaFoundationReader(file))
                {
                    MediaFoundationEncoder.EncodeToMp3(reader, outfile);
                    fileinfo.Delete();
                }
                //Setzt die BPM in den Id3-Tag
                var tfile = TagLib.File.Create(outfile);
                tfile.Tag.BeatsPerMinute = Convert.ToUInt32(bpm);
                tfile.Save();

                Debug.WriteLine("Filename: " + outfile + ", File BPM: " + bpm);
            }
        }
Ejemplo n.º 9
0
 public void Convert(string filePath)
 {
     using (var reader = new MediaFoundationReader(filePath))
     {
         MediaFoundationEncoder.EncodeToMp3(reader, GetNextFileName("convert", ".mp3"));
     }
 }
Ejemplo n.º 10
0
        static void convert_mp3()
        {
            string        filepath = ("c:\\recordings\\");
            DirectoryInfo diTarget = new DirectoryInfo(filepath);

            try
            {
                foreach (FileInfo raw in diTarget.GetFiles())
                {
                    string mp3file = Path.Combine(diTarget.FullName, raw.Name.Split(new string[] { ".wav" }, StringSplitOptions.None)[0] + ".mp3");
                    using (var reader = new WaveFileReader(raw.FullName))
                    {
                        try
                        {
                            MediaFoundationEncoder.EncodeToMp3(reader, mp3file);
                        }
                        catch (InvalidOperationException ex)
                        {
                            WriteToFile(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            // MediaFoundationEncoder.EncodeToMp3
        }
 /// <summary>
 /// 将wav转为MP3
 /// </summary>
 /// <param name="sourceFile">in wav文件</param>
 /// <param name="desFile">out MP3文件</param>
 public static void ConvertWAVtoMP3(string sourceFile, string desFile)
 {
     MediaFoundationApi.Startup();
     using (var reader = new WaveFileReader(sourceFile))
     {
         MediaFoundationEncoder.EncodeToMp3(reader, desFile);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Download finished. Starting to stream after this
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async static void AudioDownloader_DownloadFinished(object sender, EventArgs e)
        {
            var waveProvider = new MediaFoundationReader(audioPath);

            MediaFoundationEncoder.EncodeToMp3(waveProvider, mp3Path);
            await MediaMessage.Edit(string.Format("Now playing **{0}**\r\nby **{1}**", mediaName, User.Name));

            StreamFileToVoiceChannel(mp3Path, vChannelToStream);
        }
Ejemplo n.º 13
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")));
                }
            });
        }
Ejemplo n.º 14
0
 private void Convert(string path, string name)
 {
     this.SetText("Converting...");
     using (var reader = new MediaFoundationReader(path))
     {
         MediaFoundationEncoder.EncodeToMp3(reader, Path.Combine(Application.StartupPath, name + ".mp3"));
     }
     File.Delete(path);
     this.SetText("Done!");
 }
Ejemplo n.º 15
0
        public override async Task <CommandResult> RunVoiceCommand(string[] args, CommandContext context, ConnectionModel connection)
        {
            if (connection.Recording)
            {
                connection.Recording = false;
            }
            else
            {
                try
                {
                    SilenceProvider silence = new SilenceProvider(format);
                    mixer.AddInputStream(new Wave16ToFloatProvider(silence));
                    mixer.AddInputStream(new Wave16ToFloatProvider(new VolumeWaveProvider16(connection.RecordBuffer)
                    {
                        Volume = 0.1f
                    }));

                    path = Path.ChangeExtension(Path.GetTempFileName(), ".wav");

                    recorder = new WaveRecorder(mixer, path);
                    model    = connection;

                    connection.Connection.VoiceReceived += Connection_VoiceReceived;
                    connection.Disconnected             += Connection_Disconnected;
                    connection.Recording = true;

                    await context.ReplyAsync("Now recording...");

                    output = new WaveOut();
                    output.Init(new VolumeWaveProvider16(new WaveFloatTo16Provider(recorder))
                    {
                        Volume = 0.0f
                    });

                    int pingInSamples = (48000 * (connection.Connection.Ping / 1000)) * 2;
                    connection.RecordBuffer.ClearBuffer();
                    connection.RecordBuffer.AddSamples(Enumerable.Repeat((byte)0, pingInSamples).ToArray(), 0, pingInSamples);
                    output.Play();
                }
                catch { }

                while (connection.Connected && connection.Recording)
                {
                    await Task.Delay(100);
                }

                await CleanupAsync();

                string newPath = new Uri(Path.Combine(Path.GetTempPath(), $"{context.Guild.Name.ToLower()} - {DateTime.Now.ToString("dd-MM-yyyy HH-mm", CultureInfo.InvariantCulture)}.mp3")).LocalPath;
                MediaFoundationEncoder.EncodeToMp3(new WaveFileReader(path), newPath);
                await context.Channel.SendFileAsync(newPath, $"Here's your ~~clusterfuck~~ recording!");
            }

            return(CommandResult.Empty);
        }
Ejemplo n.º 16
0
 private void sendData(object st)
 {
     using (TcpClient cst = (TcpClient)st)
     {
         using (NetworkStream nstream = cst.GetStream())
             try
             {
                 byte[] buffer    = new byte[cst.ReceiveBufferSize];
                 int    bytesRead = nstream.Read(buffer, 0, cst.ReceiveBufferSize);
                 string text      = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                 if (text.Equals("base"))
                 {
                     using (StreamWriter save = new StreamWriter("base.txt"))
                     {
                         foreach (var item in tracks.Items)
                         {
                             if (!item.ToString().Contains("[") && !item.ToString().Contains("]"))
                             {
                                 save.WriteLine(item.ToString());
                             }
                         }
                     }
                     buffer = File.ReadAllBytes("base.txt");
                     nstream.Write(buffer, 0, buffer.Length);
                 }
                 else if (text.Contains("[") && text.Contains("]"))
                 {
                     buffer = Encoding.ASCII.GetBytes(tg.trackname(text.Substring(text.IndexOf("]") + 1)));
                     nstream.Write(buffer, 0, buffer.Length);
                     buffer = Encoding.ASCII.GetBytes(tg.artistname(text.Substring(text.IndexOf("]") + 1)));
                     nstream.Write(buffer, 0, buffer.Length);
                     buffer = Encoding.ASCII.GetBytes(tg.year(text.Substring(text.IndexOf("]") + 1)));
                     nstream.Write(buffer, 0, buffer.Length);
                     buffer = Encoding.ASCII.GetBytes(tg.albumname(text.Substring(text.IndexOf("]") + 1)));
                     nstream.Write(buffer, 0, buffer.Length);
                     using (MediaFoundationReader reader = new MediaFoundationReader(text.Substring(text.IndexOf("]") + 1)))
                         MediaFoundationEncoder.EncodeToMp3(reader, "file.mp3");
                     using (Stream stream = new FileStream("file.mp3", FileMode.Open, FileAccess.Read))
                     {
                         buffer = new byte[1024];
                         int length;
                         while ((length = stream.Read(buffer, 0, buffer.Length)) > 0)
                         {
                             nstream.Write(buffer, 0, length);
                         }
                     }
                 }
             }
             catch (Exception)
             {
                 cst.Close();
             }
     }
 }
Ejemplo n.º 17
0
        private static void CreateMp3File(ISampleProvider provider, string fileName)
        {
            // assumes MediaFoundationApi.Startup() was already called

            SampleToWaveProvider audioSpriteWave = new SampleToWaveProvider(provider);

            try {
                MediaFoundationEncoder.EncodeToMp3(audioSpriteWave, fileName);
            } catch (InvalidOperationException ex) {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 18
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            string soundLink = GetGUISoundLink();

            if (soundLink == "")
            {
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog();

            if (radio_mp3.Checked)
            {
                dialog.Filter   = "MP3 File (*.mp3)|*.mp3";
                dialog.FileName = "tts.mp3";
            }
            else
            {
                dialog.Filter   = "WAV File (*.wav)|*.wav";
                dialog.FileName = "tts.wav";
            }

            var s = dialog.ShowDialog();

            if (s == DialogResult.OK)
            {
                if (!Program.bOldWindows && !(radio_mp3.Checked && Math.Abs(Pitch - 1f) <= 0.01f))
                {
                    using (var mf = new MediaFoundationReader(soundLink))
                    {
                        PitchProvider             = new SmbPitchShiftingSampleProvider(mf.ToSampleProvider().ToMono());
                        PitchProvider.PitchFactor = Pitch;
                        if (radio_mp3.Checked)
                        {
                            MediaFoundationEncoder.EncodeToMp3(PitchProvider.ToWaveProvider(), dialog.FileName, 48000);
                        }
                        else
                        {
                            WaveFileWriter.CreateWaveFile(dialog.FileName, PitchProvider.ToWaveProvider());
                        }

                        MessageBox.Show(downloaded);
                    }
                }
                else
                {
                    using (var wc = new WebClient())
                    {
                        wc.DownloadFile(soundLink, dialog.FileName);
                        MessageBox.Show(downloaded);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public static void ConvertWavStreamToMp3File(ref MemoryStream ms, string savetofilename, int bitrate)
        {
            //rewind to beginning of stream
            ms.Seek(0, SeekOrigin.Begin);

            using (var retMs = new MemoryStream())
            {
                using (var rdr = new WaveFileReader(ms))
                {
                    MediaFoundationEncoder.EncodeToMp3(rdr, savetofilename + ".mp3", bitrate);
                }
            }
        }
Ejemplo n.º 20
0
        public static void ConvertM4AToMp3(Stream m4AStream, string directory, ref Track song)
        //requires windows 8 or higher
        {
            using (var reader = new StreamMediaFoundationReader(m4AStream)) //this reader supports: MP3, AAC and WAV
            {
                var aaCtype  = AudioSubtypes.MFAudioFormat_AAC;
                var bitrates = MediaFoundationEncoder.GetEncodeBitrates(aaCtype, reader.WaveFormat.SampleRate,
                                                                        reader.WaveFormat.Channels);

                song.LocalPath += ".mp3"; //conversion wil result in an mp3
                MediaFoundationEncoder.EncodeToMp3(reader, song.LocalPath, bitrates[bitrates.GetUpperBound(0)]);
            }
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
 private void ConvertWavToMp3(String input, String output)
 {
     using (var reader = new WaveFileReader(input))
     {
         try
         {
             MediaFoundationEncoder.EncodeToMp3(reader, output);
         }
         catch (InvalidOperationException ex)
         {
             log.Error("Error occured while convert wav to mp3", ex);
         }
     }
 }
Ejemplo n.º 23
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();
        }
Ejemplo n.º 24
0
 public static void ConvertWavToMp3(string wav, string mp3) // NOT TESTED  see more at     http://mark-dot-net.blogspot.ca/2015/02/how-to-encode-mp3s-with-naudio.html
 {
     try
     {
         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; }
 }
Ejemplo n.º 25
0
 private static bool ToMp3(string wavFile, string mp3File)
 {
     using (var reader = new WaveFileReader(wavFile))
     {
         try
         {
             MediaFoundationEncoder.EncodeToMp3(reader, mp3File);
             return(true);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             return(false);
         }
     }
 }
Ejemplo n.º 26
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;
        }
Ejemplo n.º 27
0
        public static void WaveToMP3MF(string inputFile, string outputFile)
        {
            MediaFoundationApi.Startup();


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

            //if (mediaType != null) { } // we can encode…


            using (var reader = new WaveFileReader(inputFile))
            {
                MediaFoundationEncoder.EncodeToMp3(reader,
                                                   outputFile, 0);
            }
        }
Ejemplo n.º 28
0
        private void MixAudio(string[] SourceAudios, string outAudio)
        {
            MixingSampleProvider mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2));

            NAudio.MediaFoundation.MediaFoundationApi.Startup();
            for (int i = 0; i < SourceAudios.Count(); i++)
            {
                var sourcefile = new AudioFileReader(SourceAudios[i]);
                var mfr        = new MediaFoundationResampler(sourcefile, WaveFormat.CreateIeeeFloatWaveFormat(44100, 2));
                mixer.AddMixerInput(mfr);
            }
            var converted16Bit = new SampleToWaveProvider16((ISampleProvider)mixer);

            using (var resampled = new MediaFoundationResampler(converted16Bit, new WaveFormat(44100, 2)))
            {
                MediaFoundationEncoder.EncodeToMp3(resampled, outAudio, 192000);
            }
            NAudio.MediaFoundation.MediaFoundationApi.Shutdown();
        }
        public void StopRecordingVoiceStream()
        {
            if (fileRecordingStream is null)
            {
                return;
            }

            fileRecordingStream.StopRecording();

            MediaFoundationApi.Startup();

            MediaFoundationEncoder.EncodeToMp3(
                fileRecordingStream.ApplyMicrophoneEffects(botConfig.MicConfiguration, new Effects.NoEffect()).ToWaveProvider(),
                fileRecordingPath);

            MediaFoundationApi.Shutdown();

            fileRecordingStream.Dispose();
            fileRecordingStream = null;
        }
Ejemplo n.º 30
0
        public static string CreateMp3File(int durationSeconds, int sampleRate = 44100, int channels = 2)
        {
            var testSignal = new SignalGenerator(sampleRate, channels)
            {
                Frequency = 1000, Gain = 0.25
            }
            .Take(TimeSpan.FromSeconds(durationSeconds))
            .ToWaveProvider();
            var path = Path.Combine(Path.GetTempPath(), "NAudioTests");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var file = Path.Combine(Path.GetTempPath(), @"NAudioTests\TestSignal.mp3");

            MediaFoundationApi.Startup();
            MediaFoundationEncoder.EncodeToMp3(testSignal, file, 96000);
            return(file);
        }