private void Encode()
        {
            if (String.IsNullOrEmpty(InputFile) || !File.Exists(InputFile))
            {
                MessageBox.Show("Please select a valid input file to convert");
                return;
            }
            if (SelectedMediaType == null || SelectedMediaType.MediaType == null)
            {
                MessageBox.Show("Please select a valid output format");
                return;
            }

            using (var reader = new MediaFoundationReader(InputFile))
            {
                string outputUrl = SelectSaveFile(SelectedOutputFormat.Name, SelectedOutputFormat.Extension);
                if (outputUrl == null)
                {
                    return;
                }
                using (var encoder = new MediaFoundationEncoder(SelectedMediaType.MediaType))
                {
                    encoder.Encode(outputUrl, reader);
                }
            }
        }
        /// <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 #3
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 #5
0
        private void Stop()
        {
            if (IsStopped)
            {
                return;
            }
            IsStopped = true;

            WaveIn?.Dispose();
            WaveIn = null;

            if (Settings.Format is not(AudioFormat.Wav or AudioFormat.Mp3) ||
                Stream is null)
            {
                return;
            }

            Stream.Position = 0;
            Data            = Stream.ToArray();

            if (Settings.Format is not AudioFormat.Mp3)
            {
                return;
            }

            var path1 = Path.GetTempFileName();
            var path2 = $"{path1}.mp3";

            try
            {
                File.WriteAllBytes(path1, Data);

                var mediaTypes = MediaFoundationEncoder
                                 .GetOutputMediaTypes(AudioSubtypes.MFAudioFormat_MP3);
                var mediaType = mediaTypes.First();

                using var reader  = new MediaFoundationReader(path1);
                using var encoder = new MediaFoundationEncoder(mediaType);
                encoder.Encode(path2, reader);

                Data = File.ReadAllBytes(path2);
            }
            finally
            {
                foreach (var path in new[] { path1, path2 })
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            }
        }
Beispiel #6
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);
                }
            }
        }
 /// <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();
     }
 }
 /// <summary>
 /// Convert WAV to AAC
 /// </summary>
 /// <param name="waveFileName"></param>
 /// <param name="mp3FileName"></param>
 /// <param name="bitRate"></param>
 public void WaveToAAC(string waveFileName, string aacFileName, int bitRate = 44100)
 {
     using (MediaFoundationReader reader = new MediaFoundationReader(waveFileName))
     {
         NAudio.MediaFoundation.MediaType mt = new NAudio.MediaFoundation.MediaType();
         mt.MajorType     = NAudio.MediaFoundation.MediaTypes.MFMediaType_Audio;
         mt.SubType       = NAudio.MediaFoundation.AudioSubtypes.MFAudioFormat_AAC;
         mt.BitsPerSample = 16;
         mt.SampleRate    = bitRate;
         mt.ChannelCount  = 2;
         using (MediaFoundationEncoder mfe = new MediaFoundationEncoder(mt))
         {
             mfe.Encode(aacFileName, reader);
         }
         //MediaFoundationEncoder.EncodeToAac(reader, aacFileName, bitRate);
     }
 }
Beispiel #9
0
        static void encode(string srcFile, string trgFile, MediaType trgMediaType)
        {
            if (string.IsNullOrEmpty(srcFile) || !File.Exists(srcFile))
            {
                Debug.WriteLine("Please select a valid input file to convert"); return;
            }
            if (!string.IsNullOrEmpty(trgFile) && File.Exists(trgFile))
            {
                File.Delete(trgFile);
            }

            using (var reader = new MediaFoundationReader(srcFile))
            {
                using (var encoder = new MediaFoundationEncoder(trgMediaType))
                {
                    encoder.Encode(trgFile, reader);
                }
            }
        }
        /// <summary>
        /// Creates an MP3-file from the downloaded video file
        /// </summary>
        /// <param name="bytesPerSecond">Audio bitrate in bytes per second</param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        private void PerformConversion(int bytesPerSecond, string input, string output)
        {
            var allMediaTypes = new Dictionary <Guid, List <MediaType> >();
            var list          = MediaFoundationEncoder.GetOutputMediaTypes(AudioSubtypes.MFAudioFormat_MP3).ToList();

            allMediaTypes[AudioSubtypes.MFAudioFormat_MP3] = list;

            // Keep audio properties from the original video file
            var supportedMediaTypes = allMediaTypes[AudioSubtypes.MFAudioFormat_MP3]
                                      .Where(m => m != null)
                                      .Where(m => m.SampleRate == inputWaveFormat.SampleRate)
                                      .Where(m => m.ChannelCount == inputWaveFormat.Channels)
                                      .ToList();

            var mediaType = supportedMediaTypes.FirstOrDefault(m => m.AverageBytesPerSecond == bytesPerSecond) ??
                            supportedMediaTypes.FirstOrDefault();

            if (mediaType != null)
            {
                using (var reader = new MediaFoundationReader(input))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(output, reader);
                    }
                }
            }

            // Cleanup before throwing cancellation
            if (tokenSource.IsCancellationRequested)
            {
                File.Delete(output);
                File.Delete(input);
                tokenSource.Token.ThrowIfCancellationRequested();
            }

            UpdateWorkStatus(WorkStatus.Finished);
        }
Beispiel #11
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}");
                }
            });
        }
        /// <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:
#if WINDOWS
                ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
#else
                throw new NotSupportedException("Adpcm encoding supported on Windows only");
#endif
                break;

            case ConversionFormat.Pcm:
#if WINDOWS
                ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
#elif LINUX
                // TODO Do the conversion for Linux platform
#else
                targetFileName = Guid.NewGuid().ToString() + ".wav";
                if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.LinearPCM, MonoMac.AudioToolbox.AudioFileType.WAVE, quality))
                {
                    throw new InvalidDataException("Failed to convert to PCM");
                }
                Read(targetFileName);
                if (File.Exists(targetFileName))
                {
                    File.Delete(targetFileName);
                }
#endif
                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:
#if WINDOWS
                ConvertWav(new ImaAdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount, 4));
#else
                throw new NotImplementedException("ImaAdpcm has not been implemented on this platform");
#endif
                break;

            case ConversionFormat.Aac:
#if WINDOWS
                reader.Position = 0;
                var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_AAC, reader.WaveFormat, QualityToBitRate(quality));
                if (mediaType == null)
                {
                    throw new InvalidDataException("Cound not find a suitable mediaType to convert to.");
                }
                using (var encoder = new MediaFoundationEncoder(mediaType)) {
                    encoder.Encode(targetFileName, reader);
                }
#elif LINUX
                // TODO: Code for Linux convertion
#else
                if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.MPEG4AAC, MonoMac.AudioToolbox.AudioFileType.MPEG4, quality))
                {
                    throw new InvalidDataException("Failed to convert to AAC");
                }
#endif
                break;

            case ConversionFormat.Vorbis:
                throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
Beispiel #13
0
        private void FilterFile(string inputFilePath, string outputFilePath)
        {
            // nothing to do if the output file already exists and is newer than both the input file and Cross Time DSP's app.config file
            if (File.Exists(outputFilePath))
            {
                DateTime inputLastWriteTimeUtc  = File.GetLastWriteTimeUtc(inputFilePath);
                DateTime outputLastWriteTimeUtc = File.GetLastWriteTimeUtc(outputFilePath);
                if ((outputLastWriteTimeUtc > inputLastWriteTimeUtc) &&
                    (outputLastWriteTimeUtc > this.Configuration.LastWriteTimeUtc))
                {
                    this.log.ReportVerbose("'{0}': skipped as '{1}' is newer.", Path.GetFileName(inputFilePath), Path.GetFileName(outputFilePath));
                    return;
                }
            }

            // get input
            DateTime processingStartedUtc     = DateTime.UtcNow;
            MediaFoundationReader inputStream = new MediaFoundationReader(inputFilePath);

            if (Constant.SampleBlockSizeInBytes % inputStream.WaveFormat.BlockAlign != 0)
            {
                this.log.ReportError("'{0}': cannot be processed as sample block size of {0} bytes is not an exact multiple of the input block alignment of {1} bytes.", Path.GetFileName(inputFilePath), Constant.SampleBlockSizeInBytes, inputStream.WaveFormat.BlockAlign);
                return;
            }

            // ensure output directory exists so that output file write succeeds
            string outputDirectoryPath = Path.GetDirectoryName(outputFilePath);

            if (String.IsNullOrEmpty(outputDirectoryPath) == false && Directory.Exists(outputDirectoryPath) == false)
            {
                Directory.CreateDirectory(outputDirectoryPath);
            }

            StreamPerformance streamMetrics;

            using (WaveStream outputStream = this.FilterStream(inputStream, out streamMetrics))
            {
                // do the filtering
                if (this.Stopping)
                {
                    // if the stop flag was set during filtering outputStream will be null
                    return;
                }

                // write output file
                MediaType outputMediaType;
                if (this.Configuration.Output.Encoding == Encoding.Wave)
                {
                    // work around NAudio bug: MediaFoundationEncoder supports Wave files but GetOutputMediaTypes() fails on Wave
                    outputMediaType = new MediaType(outputStream.WaveFormat);
                }
                else
                {
                    List <MediaType> outputMediaTypes = MediaFoundationEncoder.GetOutputMediaTypes(Constant.EncodingGuids[this.Configuration.Output.Encoding]).Where(mediaType => mediaType.BitsPerSample == outputStream.WaveFormat.BitsPerSample && mediaType.ChannelCount == outputStream.WaveFormat.Channels && mediaType.SampleRate == outputStream.WaveFormat.SampleRate).ToList();
                    if ((outputMediaTypes == null) || (outputMediaTypes.Count < 1))
                    {
                        this.log.ReportError("'{0}': no media type found for {1} bits per sample, {2} channels, at {3} kHz.", Path.GetFileName(inputFilePath), outputStream.WaveFormat.BitsPerSample, outputStream.WaveFormat.Channels, outputStream.WaveFormat.SampleRate);
                        return;
                    }
                    outputMediaType = outputMediaTypes[0];
                }
                MediaFoundationEncoder outputEncoder = new MediaFoundationEncoder(outputMediaType);
                streamMetrics.EncodingStartedUtc = DateTime.UtcNow;
                outputEncoder.Encode(outputFilePath, outputStream);
                streamMetrics.EncodingStoppedUtc = DateTime.UtcNow;
            }

            // copy metadata
            Tag inputMetadata;

            using (FileStream inputMetadataStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (TagFile inputTagFile = TagFile.Create(new StreamFileAbstraction(inputMetadataStream.Name, inputMetadataStream, inputMetadataStream)))
                {
                    inputMetadata = inputTagFile.Tag;
                }
            }

            using (FileStream outputMetadataStream = new FileStream(outputFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
            {
                using (TagFile outputTagFile = TagFile.Create(new StreamFileAbstraction(outputMetadataStream.Name, outputMetadataStream, outputMetadataStream)))
                {
                    if (this.TryApplyMetadata(inputMetadata, outputTagFile.Tag))
                    {
                        outputTagFile.Save();
                    }
                }
            }

            DateTime processingStoppedUtc = DateTime.UtcNow;
            TimeSpan encodingTime         = streamMetrics.EncodingStoppedUtc - streamMetrics.EncodingStartedUtc;
            TimeSpan processingTime       = processingStoppedUtc - processingStartedUtc;

            if (streamMetrics.HasReverseTime)
            {
                TimeSpan reverseBufferTime     = streamMetrics.ReverseBufferCompleteUtc - streamMetrics.StartTimeUtc;
                TimeSpan reverseProcessingTime = streamMetrics.ReverseTimeCompleteUtc - streamMetrics.ReverseBufferCompleteUtc;
                if (streamMetrics.HasForwardTime)
                {
                    TimeSpan forwardProcessingTime = streamMetrics.CompleteTimeUtc - streamMetrics.ReverseTimeCompleteUtc;
                    this.log.ReportVerbose("'{0}' to '{1}' in {2} (buffer {3}, reverse {4}, forward {5}, encode {6}).", Path.GetFileName(inputFilePath), Path.GetFileName(outputFilePath), processingTime.ToString(Constant.ElapsedTimeFormat), reverseBufferTime.ToString(Constant.ElapsedTimeFormat), reverseProcessingTime.ToString(Constant.ElapsedTimeFormat), forwardProcessingTime.ToString(Constant.ElapsedTimeFormat), encodingTime.ToString(Constant.ElapsedTimeFormat));
                }
                else
                {
                    this.log.ReportVerbose("'{0}' to '{1}' in {2} (buffer {3}, reverse {4}, encode {5}).", Path.GetFileName(inputFilePath), Path.GetFileName(outputFilePath), processingTime.ToString(Constant.ElapsedTimeFormat), reverseBufferTime.ToString(Constant.ElapsedTimeFormat), reverseProcessingTime.ToString(Constant.ElapsedTimeFormat), encodingTime.ToString(Constant.ElapsedTimeFormat));
                }
            }
            else
            {
                TimeSpan filteringTime = streamMetrics.CompleteTimeUtc - streamMetrics.StartTimeUtc;
                this.log.ReportVerbose("'{0}' to '{1}' in {2} (load+filter {3}, encode {4}).", Path.GetFileName(inputFilePath), Path.GetFileName(outputFilePath), processingTime.ToString(Constant.ElapsedTimeFormat), filteringTime.ToString(Constant.ElapsedTimeFormat), encodingTime.ToString(Constant.ElapsedTimeFormat));
            }
        }
        public static async void Test()
        {
            try
            {
                var mt = new MediaType
                {
                    ChannelCount = 2,
                    //AverageBytesPerSecond = 32000,
                    SampleRate = 48000
                };



                using (var reader = new MediaFoundationReader(tw))
                {
                    string outputUrl = tm;           if (outputUrl == null)
                    {
                        return;
                    }


                    using (var encoder = new MediaFoundationEncoder(mt))
                    {
                        encoder.Encode(outputUrl, reader);
                    }
                }



                foreach (var f in Directory.GetFiles(@"C:\temp", "*.WAV"))
                {
                    ConvertWavToMp3(f, f + ".mp3");
                }

                SpeechSynthesizer synth = new SpeechSynthesizer();

                var fi = new SpeechAudioFormatInfo(4000, AudioBitsPerSample.Eight, AudioChannel.Stereo);
                /// 48000x8 = 384
                /// 48000x16 = 768
                synth.SetOutputToWaveFile(tw, fi);
                synth.SpeakCompleted += new EventHandler <SpeakCompletedEventArgs>(synth_SpeakCompleted);

                var builder = new PromptBuilder();
                builder.AppendText("This sample asynchronously speaks a prompt to a WAVE file.");

                synth.SpeakAsync(builder);



                var wav = @"D:\Users\alex\Videos\0Pod\Cuts\BPr-6659,`Hacking Addiction with Dr. Mark – #351\[002].--- 70 ---.wav";
                var mp3 = @"D:\Users\alex\Videos\0Pod\Cuts\BPr-6659,`Hacking Addiction with Dr. Mark – #351\[002].--- 70 ---.mp3";
                //NAudioHelper.ConvertWavToMp3(wav, mp3);

                await Task.Delay(999);

                Thread.Sleep(1500);
            }
            catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, System.Reflection.MethodInfo.GetCurrentMethod().Name); if (System.Diagnostics.Debugger.IsAttached)
                                   {
                                       System.Diagnostics.Debugger.Break();
                                   }
                                   throw; }
        }
        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; }
        }