/// <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);
     }
 }
예제 #2
0
        public override void ProcessItem(IJob job, IJobItem item)
        {
            var bitRate = job.Preset.BitRate;
            var sampleRate = job.Preset.SampleRate;
            var tempdir = Path.GetTempPath();
            var tempfile = Path.Combine(tempdir, DateTime.Now.Ticks + "." + job.Preset.Extension);

            var subType = this.GetAudioSubtypeForExtension(job.Preset.Extension);
            var waveFormat = new WaveFormat(sampleRate, 2);

            var mediaType = MediaFoundationEncoder.SelectMediaType(subType, waveFormat, bitRate);

            if (mediaType != null)
            {
                using (var decoder = new MediaFoundationReader(item.LastFile))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(tempfile, decoder);
                    }
                }
            }

            item.TemporaryFiles.Add(tempfile);
        }
 /// <summary>
 /// Helper function to simplify encoding to MP3
 /// By default, will only be available on Windows 8 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp3</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         encoder.Encode(outputFile, inputProvider);
     }
 }
        /// <summary>
        /// Helper function to simplify encoding to MP3
        /// By default, will only be available on Windows 8 and above
        /// </summary>
        /// <param name="inputProvider">Input provider, must be PCM</param>
        /// <param name="outputFile">Output file path, should end with .mp3</param>
        /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
        public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
        {
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);

            using (var encoder = new MediaFoundationEncoder(mediaType))
            {
                encoder.Encode(outputFile, inputProvider);
            }
        }
예제 #5
0
 /// <summary>
 /// Helper function to simplify encoding to MP3
 /// By default, will only be available on Windows 8 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp3</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);
     if (mediaType == null) throw new InvalidOperationException("No suitable MP3 encoders available");
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         encoder.Encode(outputFile, inputProvider);
     }
 }
 /// <summary>
 /// Helper function to simplify encoding to AAC
 /// By default, will only be available on Windows 7 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp4 (or .aac on Windows 8)</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToAac(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     // Information on configuring an AAC media type can be found here:
     // http://msdn.microsoft.com/en-gb/library/windows/desktop/dd742785%28v=vs.85%29.aspx
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_AAC, inputProvider.WaveFormat, desiredBitRate);
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         // should AAC container have ADTS, or is that just for ADTS?
         // http://www.hydrogenaudio.org/forums/index.php?showtopic=97442
         encoder.Encode(outputFile, inputProvider);
     }
 }
예제 #7
0
 public static void EncodeToWma(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     MediaType mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_WMAudioV8, inputProvider.WaveFormat, desiredBitRate);
     if (mediaType == null)
     {
         throw new InvalidOperationException("No suitable WMA encoders available");
     }
     using (MediaFoundationEncoder mediaFoundationEncoder = new MediaFoundationEncoder(mediaType))
     {
         mediaFoundationEncoder.Encode(outputFile, inputProvider);
     }
 }
        /// <summary>
        /// Helper function to simplify encoding to AAC
        /// By default, will only be available on Windows 7 and above
        /// </summary>
        /// <param name="inputProvider">Input provider, must be PCM</param>
        /// <param name="outputFile">Output file path, should end with .mp4 (or .aac on Windows 8)</param>
        /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
        public static void EncodeToAac(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
        {
            // Information on configuring an AAC media type can be found here:
            // http://msdn.microsoft.com/en-gb/library/windows/desktop/dd742785%28v=vs.85%29.aspx
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_AAC, inputProvider.WaveFormat, desiredBitRate);

            using (var encoder = new MediaFoundationEncoder(mediaType))
            {
                // should AAC container have ADTS, or is that just for ADTS?
                // http://www.hydrogenaudio.org/forums/index.php?showtopic=97442
                encoder.Encode(outputFile, inputProvider);
            }
        }
예제 #9
0
 private void Encode()
 {
     using (var reader = new MediaFoundationReader(_fileLocation))
     {
         var SelectedOutputFormat = new Encoder()
         {
             Name = "MP3",
             Guid = AudioSubtypes.MFAudioFormat_MP3,
             Extension = ".mp3"
         };
         var list = MediaFoundationEncoder.GetOutputMediaTypes(SelectedOutputFormat.Guid)
                           .Select(mf => new MediaTypeUtils(mf))
                           .ToList();
         string outputUrl = SelectSaveFile();
         if (outputUrl == null) return;
         using (var encoder = new MediaFoundationEncoder(list[0].MediaType))
         {
             encoder.Encode(outputUrl, reader);
         }
     }
 }
        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);
                }
            }
        }
예제 #11
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:
#if WINDOWS
                    ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;
#else
                    throw new NotSupportedException("Adpcm encoding supported on Windows only");
#endif

                case ConversionFormat.Pcm:
#if WINDOWS
                    ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;
#elif LINUX
                    // TODO Do the conversion for Linux platform
                    throw new NotSupportedException("Pcm has not been implemented on this platform");
#else //MONOMAC
                    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);
                    break;
#endif

                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));
                    break;
#else
                    throw new NotImplementedException("ImaAdpcm has not been implemented on this platform");
#endif

                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);
                    }
                    break;
#elif LINUX
                    // TODO: Code for Linux convertion
                    throw new NotImplementedException("Aac has not been implemented on this platform");
#else //MONOMAC
                    if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.MPEG4AAC, MonoMac.AudioToolbox.AudioFileType.MPEG4, quality)) {
                        throw new InvalidDataException("Failed to convert to AAC");
                    }
                    break;
#endif

                case ConversionFormat.Vorbis:
                    throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
        /// <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);
        }