/// <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);
     }
 }
        public void Convert()
        {
            var tempWavFile = GetTemporaryWavFileName();
            var bitRate = new TagLibEditor().GetBitRate(wmaFile);

            using (var reader = new MediaFoundationReader(wmaFile))
            {
                WaveFileWriter.CreateWaveFile(tempWavFile, reader);
            }

            var mp3 = new LameConverter(tempWavFile, mp3File, bitRate);
            mp3.Convert();
        }
        public override void ProcessItem(IJob job, IJobItem item)
        {
            var tempfile = Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks + ".wav");
            item.TemporaryFiles.Add(tempfile);

            using (var reader = new MediaFoundationReader(item.SourceFile))
            {
                WaveFileWriter.CreateWaveFile(tempfile, reader);
            }
        }
        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);
        }
Beispiel #5
0
        private void RefreshPlayList()
        {
            ls.Clear();
            List <Association> temp = new List <Association>(pl);

            foreach (Association s in temp)
            {
                try
                {
                    NAudio.Wave.MediaFoundationReader a;
                    try
                    {
                        a = new NAudio.Wave.MediaFoundationReader(s.Path);
                    }
                    catch
                    {
                        a = new NAudio.Wave.MediaFoundationReader(s.Path);
                    }
                    ls.Add(new Items()
                    {
                        Name = s.Name, Time = FillWithZero(a.TotalTime.Minutes.ToString()) + ":" + FillWithZero(a.TotalTime.Seconds.ToString())
                    });
                    a.Dispose();
                }
                catch
                {
                    MessageBox.Show("Nie udało się załadować wszytkich plików muzycznych! Sprawdź lokalizację plików!");
                    pl.Remove(FindObject(s.Name));
                    continue;
                }
            }
            Playlist.ItemsSource = ls;
            Playlist.Items.Refresh();
        }
 /// <summary>
 /// Convert WAV to WMA 
 /// </summary>
 /// <param name="waveFileName"></param>
 /// <param name="mp3FileName"></param>
 /// <param name="bitRate"></param>
 public void WaveToWMA(string waveFileName, string wmaFileName, int bitRate = 44100)
 {
     using (MediaFoundationReader reader = new MediaFoundationReader(waveFileName))
     {
         MediaFoundationEncoder.EncodeToWma(reader, wmaFileName, bitRate);
     }
 }
Beispiel #7
0
        private void PerformEncode(IMFSinkWriter writer, int streamIndex, MediaFoundationReader inputProvider, int first, int last)
        {
            int maxLength     = inputProvider.WaveFormat.AverageBytesPerSecond * 4;
            var managedBuffer = new byte[maxLength];

            writer.BeginWriting();

            first++;
            bool   flag     = true;
            double time     = Math.Round(inputProvider.TotalTime.TotalSeconds - last, 0);
            long   position = 0;
            long   duration;

            do
            {
                duration  = ConvertOneBuffer(writer, streamIndex, inputProvider, position, managedBuffer, first, ref flag);
                position += duration;

                int percent = (int)(inputProvider.CurrentTime.TotalSeconds / inputProvider.TotalTime.TotalSeconds * 100);
                //LoadProgressChanged.Raise(this, new LoadProgressChangedEventArgs(percent, inputProvider.CurrentTime, inputProvider.TotalTime));
                OnLoadProgressChanged(percent, inputProvider.CurrentTime, inputProvider.TotalTime);

                if (inputProvider.CurrentTime.TotalSeconds >= time)
                {
                    duration = 0;
                }
            } while (duration > 0);

            writer.DoFinalize();
        }
Beispiel #8
0
        /// <summary>
        /// Encodes a file
        /// </summary>
        /// <param name="outputFile">Output filename (container type is deduced from the filename)</param>
        /// <param name="inputProvider">Input provider (should be PCM, some encoders will also allow IEEE float)</param>
        /// <param name="first">How many seconds to crop the file from the front</param>
        /// <param name="last">How many seconds to crop the file from the back</param>
        public void Encode(string outputFile, MediaFoundationReader inputProvider, int first, int last)
        {
            if (inputProvider.WaveFormat.Encoding != WaveFormatEncoding.Pcm && inputProvider.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
            {
                throw new ArgumentException("Encode input format must be PCM or IEEE float");
            }

            var inputMediaType = new MediaType(inputProvider.WaveFormat);

            var writer = CreateSinkWriter(outputFile);

            try
            {
                int streamIndex;
                writer.AddStream(outputMediaType.MediaFoundationObject, out streamIndex);

                // n.b. can get 0xC00D36B4 - MF_E_INVALIDMEDIATYPE here
                writer.SetInputMediaType(streamIndex, inputMediaType.MediaFoundationObject, null);

                PerformEncode(writer, streamIndex, inputProvider, first, last);
            }
            finally
            {
                Marshal.ReleaseComObject(writer);
                Marshal.ReleaseComObject(inputMediaType.MediaFoundationObject);
                //LoadComplete.Raise(this, EventArgs.Empty);
                OnLoadComplete();
            }
        }
Beispiel #9
0
 internal static void ConvertToAAC(string sFile, string sPath)
 {
     using (var reader = new MediaFoundationReader(sFile))
     {
         MediaFoundationEncoder.EncodeToAac(reader, sPath + "hi.m4a");
     }
 }
Beispiel #10
0
 /// <summary>
 /// Converts mp4 file's audio to mp3. It will throw an exception if Media Foundation codec not installed.
 /// </summary>
 /// <param name="inputFile"></param>
 /// <param name="outputFile"></param>
 public static void ConvertMp4ToMp3(string inputFile, string outputFile)
 {
     using (var reader = new NAudio.Wave.MediaFoundationReader(inputFile))
     {
         using (var writer = new NAudio.Lame.LameMP3FileWriter(outputFile, reader.WaveFormat, NAudio.Lame.LAMEPreset.V2))
         {
             reader.CopyTo(writer);
         }
     }
 }
Beispiel #11
0
        /// <summary>
        /// Helper function to simplify encoding Window Media Audio
        /// Should be supported on Vista and above (not tested)
        /// </summary>
        /// <param name="inputProvider">Input provider, must be PCM</param>
        /// <param name="outputFile">Output file path, should end with .wma</param>
        /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
        public static void EncodeToWma(MediaFoundationReader inputProvider, string outputFile, int desiredBitRate = 192_000)
        {
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_WMAudioV8, inputProvider.WaveFormat, desiredBitRate);

            if (mediaType == null)
            {
                throw new InvalidOperationException("No suitable WMA encoders available");
            }
            using (var encoder = new MediaFoundationEncoder(mediaType))
            {
                encoder.Encode(outputFile, inputProvider, 0, 0);
            }
        }
 public void CanReadAnAac()
 {
     var testFile = @"C:\Users\mheath\Downloads\NAudio\AAC\halfspeed.aac";
     var reader = new MediaFoundationReader(testFile);
     Console.WriteLine(reader.WaveFormat);
     var buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
     int bytesRead;
     long total = 0;
     while((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
     {
         total += bytesRead;
     }
     Assert.IsTrue(total > 0);
 }
Beispiel #13
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>
        /// <param name="first">How many seconds to crop the file from the front</param>
        /// <param name="last">How many seconds to crop the file from the back</param>
        public void EncodeToMp3(MediaFoundationReader inputProvider, string outputFile, int desiredBitRate = 192000, int first = 0, int last = 0)
        {
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);

            if (mediaType == null)
            {
                throw new InvalidOperationException("No suitable MP3 encoders available");
            }
            Encode(outputFile, inputProvider, first, last);
            //using (var encoder = new MediaFoundationEncoder(mediaType))
            //{
            //    encoder.Encode(outputFile, inputProvider, first, last);
            //}
        }
Beispiel #14
0
        public static void Mp3ToWav(string mp3File, string outputFile)
        {
            using (Mp3FileReader reader = new Mp3FileReader(mp3File))
            {
                using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(reader))
                {
                    WaveFileWriter.CreateWaveFile(outputFile, pcmStream);
                }

                using (var reader2 = new MediaFoundationReader(outputFile))
                {
                    string newMp3 = string.Format("New{0}", mp3File);
                    MediaFoundationEncoder.EncodeToMp3(reader2, newMp3, 192000);
                }
            }
        }
 private bool TryOpenInputFile(string file)
 {
     bool isValid = false;
     try
     {
         using (var reader = new MediaFoundationReader(file))
         {
             InputFormat = reader.WaveFormat.ToString();
             inputWaveFormat = reader.WaveFormat;
             isValid = true;
         }
     }
     catch (Exception e)
     {
         MessageBox.Show(String.Format("Not a supported input file ({0})", e.Message));
     }
     return isValid;
 }
 public IWaveProvider Load(string fileName)
 {
     WaveStream readerStream = null;
     if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)){
         readerStream = new WaveFileReader(fileName);
         if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
         {
             readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
             readerStream = new BlockAlignReductionStream(readerStream);
         }
     }else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)){
         readerStream = new Mp3FileReader(fileName);
     }else if (fileName.EndsWith(".aiff")){
         readerStream = new AiffFileReader(fileName);
     }else{
         readerStream = new MediaFoundationReader(fileName);
     }
     return readerStream;
 }
        public void Execute()
        {
            if(this.StreamStarted != null)
                this.StreamStarted(this, EventArgs.Empty);

            MediaFoundationReader reader = new MediaFoundationReader(this.Video.DownloadUrl);
            WaveOut player = new WaveOut(); 
            player.Init(reader);
            player.Play();
            
            while(player.PlaybackState != PlaybackState.Stopped)
            {
                if (this.StreamPositionChanged != null)
                    this.StreamPositionChanged(this, new ProgressEventArgs(reader.CurrentTime.Seconds * reader.TotalTime.Seconds / 100));
                Thread.Sleep(1000);
            }

            if(this.StreamFinished != null)
                this.StreamFinished(this, EventArgs.Empty);

            player.Dispose();
        }
Beispiel #18
0
        public void Play()
        {
            var file = Path.Combine(BasicTeraData.Instance.ResourceDirectory, "sound/", File);
            try
            {
                var outputStream = new MediaFoundationReader(file);
                var volumeStream = new WaveChannel32(outputStream);
                volumeStream.Volume = Volume;
                //Create WaveOutEvent since it works in Background and UI Threads
                var player = new DirectSoundOut();
                //Init Player with Configured Volume Stream
                player.Init(volumeStream);
                player.Play();

                var timer = new Timer((obj) =>
                {
                    player.Stop();
                    player.Dispose();
                    volumeStream.Dispose();
                    outputStream.Dispose();
                    outputStream = null;
                    player = null;
                    volumeStream = null;
                }, null, Duration, Timeout.Infinite);
            }
            catch (Exception e)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(e, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                BasicTeraData.LogError("Sound ERROR test" + e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException + Environment.NewLine + e + Environment.NewLine + "filename:" + file + Environment.NewLine + "line:" + line, false, true);
            }
        }
Beispiel #19
0
        private void openButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                stopPreview_Click(sender, e);
                if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".wav")
                {
                    originalFile = File.ReadAllBytes(openFileDialog1.FileName);
                }
                else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".mp3")
                {
                    using (var reader = new NAudio.Wave.Mp3FileReader(openFileDialog1.FileName))
                    {
                        using (MemoryStream wavCreate = new MemoryStream())
                        {
                            NAudio.Wave.WaveFileWriter.WriteWavFileToStream(wavCreate, reader);
                            originalFile = wavCreate.ToArray();
                        }
                    }
                }
                else if (Path.GetExtension(openFileDialog1.FileName).ToLower() == ".flac")
                {
                    using (var reader = new NAudio.Wave.MediaFoundationReader(openFileDialog1.FileName))
                    {
                        using (MemoryStream wavCreate = new MemoryStream())
                        {
                            NAudio.Wave.WaveFileWriter.WriteWavFileToStream(wavCreate, reader);
                            originalFile = wavCreate.ToArray();
                        }
                    }
                }
                channels = originalFile[22];
                switch (channels)
                {
                case 1:
                    oneCh.Checked = true;
                    break;

                case 2:
                    twoCh.Checked = true;
                    break;

                case 3:
                    threeCh.Checked = true;
                    break;

                case 4:
                    fourCh.Checked = true;
                    break;

                case 5:
                    fiveCh.Checked = true;
                    break;

                case 6:
                    sixCh.Checked = true;
                    break;

                default:
                    MessageBox.Show("Invalid WAV file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                bitDepth = originalFile[34];
                switch (bitDepth)
                {
                case 8:
                    eightBit.Checked = true;
                    break;

                case 16:
                    DimaBachilo.Checked = true;
                    break;

                case 24:
                    twentyFourBit.Checked = true;
                    break;

                case 32:
                    thirtyTwoBit.Checked = true;
                    break;

                default:
                    MessageBox.Show("Invalid WAV file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                byte[] frequency = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    frequency[i] = originalFile[i + 24];
                }
                byte[] dataSizeByte = new byte[4];
                if (originalFile[35] == 0 && originalFile[36] == 100 && originalFile[37] == 97 && originalFile[38] == 116 && originalFile[39] == 97)
                {
                    dataStartOffset = 0;
                }
                else
                {
                    for (int i = 1; i < originalFile.Length - 4; i++)
                    {
                        if (originalFile[35 + i] == 0 && originalFile[36 + i] == 100 && originalFile[37 + i] == 97 && originalFile[38 + i] == 116 && originalFile[39 + i] == 97)
                        {
                            dataStartOffset = i;
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                for (int i = 0; i < 4; i++)
                {
                    dataSizeByte[i] = originalFile[i + dataStartOffset + 40];
                }
                dataSize      = Convert.ToInt32(LEtoDecByte(dataSizeByte));
                textBox1.Text = openFileDialog1.FileName;
                textBox1.Select(textBox1.Text.Length, 0);
                textBox1.ScrollToCaret();
                freq          = LEtoDecByte(frequency);
                textBox2.Text = freq;
                enableButtons(true);
                checkBox1.Enabled     = true;
                previewButton.Enabled = true;
                saveButton.Enabled    = true;
                checkBox1.Checked     = false;
                swappedFile           = null;
            }
        }
Beispiel #20
0
 /// <summary>
 /// Gets the duration based on MediaFoundation APIs
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static TimeSpan GetMediaFoundationDurationMP3(string file)
 {
     using (var reader = new MediaFoundationReader(file))
     {
         return reader.TotalTime;
     }
 }
Beispiel #21
0
        /// <summary>
        /// Sets the track.
        /// </summary>
        /// <param name="trackId">The track identifier.</param>
        public void SetTrack(string trackId)
        {
            CurrentSong = trackId;
            LibraryTrack track = library.GetTrack(trackId);
            if (track != null)
            {
                WaveStream stream;
                if (Path.GetExtension(track.Path) == ".flac")
                {
                    var flac = new FlacBox.WaveOverFlacStream(new FlacBox.FlacReader(File.OpenRead(track.Path), false));
                    stream = new RawSourceWaveStream(flac, new WaveFormat());
                }
                else
                {
                    stream = new MediaFoundationReader(track.Path);
                }

                try
                {
                    waveOutDevice.Init(stream);
                }
                catch
                {
                    nextCallback();
                }
            }
            else
            {
                nextCallback();
            }
        }
Beispiel #22
0
        private static void VoiceStuffs(DiscordVoiceClient vc, string file)
        {
            try
            {
                int ms = 60;
                int channels = 1;
                int sampleRate = 48000;

                int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds
                byte[] buffer = new byte[blockSize];
                var outFormat = new WaveFormat(sampleRate, 16, channels);
                
                vc.SetSpeaking(true);
                using (var mp3Reader = new MediaFoundationReader(file))
                {
                    using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 })
                    {
                        //resampler.ResamplerQuality = 60;
                        int byteCount;
                        while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0)
                        {
                            if (vc.Connected)
                            {
                                vc.SendVoice(buffer);
                            }
                            else
                                break;
                        }
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Voice finished enqueuing");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                }
            }
            catch (Exception ex)
            {
                owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```");
            }
        }
        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);
                }
            }
        }
 private bool TryOpenInputFile(string file)
 {
     bool isValid = false;
     try
     {
         using (var tempReader = new MediaFoundationReader(file))
         {
             DefaultDecompressionFormat = tempReader.WaveFormat.ToString();
             InputPath = file;
             isValid = true;
         }
     }
     catch (Exception e)
     {
         MessageBox.Show(String.Format("Not a supported input file ({0})", e.Message));
     }
     return isValid;
 }
        //requires windows 8 or higher
        public static bool ConvertM4aToMp3(byte[] m4aFile, string directory, ref Track song)
        {
            var tempFile = Path.Combine(directory, "tempdata" + uniqueTempFileCounter + ".m4a");
            //

            try
            {
                uniqueTempFileCounter += 1;
                System.IO.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
                {
                    Guid AACtype = AudioSubtypes.MFAudioFormat_AAC;
                    int[] 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 e)
            {
                Debug.WriteLine(e);
                if(File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                return false;
            }
        }
        private void TestRheaStream()
        {
            DiscordVoiceClient vc = client.GetVoiceClient();
            try
            {
                int ms = voiceMsBuffer;
                int channels = 1;
                int sampleRate = 48000;

                int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds
                byte[] buffer = new byte[blockSize];
                var outFormat = new WaveFormat(sampleRate, 16, channels);
                vc.SetSpeaking(true);
                using (var mp3Reader = new MediaFoundationReader("http://radiosidewinder.out.airtime.pro:8000/radiosidewinder_a"))
                {
                    using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 })
                    {
                        int byteCount;
                        while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0)
                        {
                            if (vc.Connected)
                            {
                                vc.SendVoice(buffer);
                            }
                            else
                                break;
                        }
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Voice finished enqueuing");
                        Console.ForegroundColor = ConsoleColor.White;
                        resampler.Dispose();
                        mp3Reader.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```");
            }
        }
Beispiel #27
0
        private async Task RequestCommand(CommandEventArgs e)
        {
                var urlToDownload = e.Args[0];
                var newFilename = Guid.NewGuid().ToString();
                var mp3OutputFolder = @"c:\mp3\";

            if (urlToDownload.Contains("soundcloud"))
            {
                Track track = _soundCloud.GetTrack(e.Args[0]);
                string inPath = Path.Combine(mp3OutputFolder, newFilename + ".mp3");

                if (!track.Streamable)
                {
                    await e.Channel.SendMessage("\"" + track.Title + "\" is not streamable :C");
                }

                try
                {
                    using (var client = new WebClient())
                    {
                        client.DownloadFile(track.StreamUrl + "?client_id=" + _soundCloud.ClientID, inPath);
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }

                var outFile = inPath.Remove(inPath.Length - 4) + "_c" + ".wav";

                try
                {
                    using (var reader = new MediaFoundationReader(inPath))
                    {
                        var outFormat = new WaveFormat(48000, 16, 2);
                        using (var resampler = new MediaFoundationResampler(reader, outFormat))
                        {
                            resampler.ResamplerQuality = 60;
                            VolumeWaveProvider16 vol = new VolumeWaveProvider16(resampler);
                            vol.Volume = 0.3f;
                            WaveFileWriter.CreateWaveFile(outFile, vol);
                        }
                    }

                    File.Delete(inPath);

                }
                catch (Exception e2)
                {
                    Console.Write(e2.ToString());
                    return;
                }

                await e.Channel.SendMessage("Added \"" + track.Title + "\" to the queue. It will be played soon.");

                _queue.musicQueue.Enqueue(Tuple.Create<string, string>(outFile, track.Title));
                Thread thread = new Thread(() => { _queue.PlayNextMusicToAllVoiceClients(); });
                thread.Start();

            }
            else
            {

                IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(e.Args[0]);

                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                string inPath = Path.Combine(mp3OutputFolder, newFilename + video.AudioExtension);

                try
                {
                    var audioDownloader = new AudioDownloader(video, inPath);
                    audioDownloader.Execute();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error while trying to download youtube link.");
                    Console.Write(ex.ToString());
                }

                var outFile = inPath.Remove(inPath.Length - 4) + "_c" + ".wav";

                try
                {
                    using (var reader = new MediaFoundationReader(inPath))
                    {
                        var outFormat = new WaveFormat(48000, 16, 2);
                        using (var resampler = new MediaFoundationResampler(reader, outFormat))
                        {
                            resampler.ResamplerQuality = 60;
                            VolumeWaveProvider16 vol = new VolumeWaveProvider16(resampler);
                            vol.Volume = 0.3f;
                            WaveFileWriter.CreateWaveFile(outFile, vol);
                        }
                    }

                    File.Delete(inPath);

                }
                catch (Exception e2)
                {
                    Console.Write(e2.ToString());
                    return;
                }

                await e.Channel.SendMessage("Added \"" + video.Title + "\" to the queue. It will be played soon.");

                _queue.musicQueue.Enqueue(Tuple.Create<string, string>(outFile, video.Title));

                Thread thread = new Thread(() => { _queue.PlayNextMusicToAllVoiceClients(); });
                thread.Start();
            }
        }
Beispiel #28
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);
         }
     }
 }
Beispiel #29
0
        private void SendVoice(string file, DiscordClient client)
        {
            DiscordVoiceClient vc = client.GetVoiceClient();
            try
            {
                int ms = vc.VoiceConfig.FrameLengthMs;
                int channels = vc.VoiceConfig.Channels;
                int sampleRate = 48000;

                int blockSize = 48 * 2 * channels * ms; //sample rate * 2 * channels * milliseconds
                byte[] buffer = new byte[blockSize];
                var outFormat = new WaveFormat(sampleRate, 16, channels);

                vc.SetSpeaking(true);
                if (file.EndsWith(".wav"))
                {
                    using (var waveReader = new WaveFileReader(file))
                    {
                        int byteCount;
                        while ((byteCount = waveReader.Read(buffer, 0, blockSize)) > 0)
                        {
                            if (vc.Connected)
                                vc.SendVoice(buffer);
                            else
                                break;
                        }
                    }
                }
                else if (file.EndsWith(".mp3"))
                {
                    using (var mp3Reader = new MediaFoundationReader(file))
                    {
                        using (var resampler = new MediaFoundationResampler(mp3Reader, outFormat) { ResamplerQuality = 60 })
                        {
                            //resampler.ResamplerQuality = 60;
                            int byteCount;
                            while ((byteCount = resampler.Read(buffer, 0, blockSize)) > 0)
                            {
                                if (vc.Connected)
                                {
                                    vc.SendVoice(buffer);
                                }
                                else
                                    break;
                            }
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Voice finished enqueuing");
                            Console.ForegroundColor = ConsoleColor.White;
                            resampler.Dispose();
                            mp3Reader.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    MainEntry.owner.SendMessage("Exception during voice: `" + ex.Message + "`\n\n```" + ex.StackTrace + "\n```");
                }
                catch { }
            }
        }
 public async Task SendWav(string pathToWav)
 {
     using (var reader = new MediaFoundationReader(pathToWav))
     {
         byte[] buffer = new byte[reader.Length];
         await reader.ReadAsync(buffer, 0, buffer.Length);
         await SendPacket(GeneratePacket(buffer, 0));
     }
 }
Beispiel #31
0
        public void PlayPlayListItem(PlayListItem playListItem)
        {
            if (playListItem == null)
                return;

            _currentlyPlayListItem = playListItem;
            ShowPlayer();

            if (_currentlyPlayListItem.Type == PlayListItemType.Video || 
                _currentlyPlayListItem.Type == PlayListItemType.Audio)
            {
                if (playListItem.SupportsMultiCast && playListItem.Screen == null)
                    throw new Exception("No Screen Setup");

                if (playListItem.StartMin > 0 || playListItem.StartSec > 0)
                {
                    wmPlayer.Ctlcontrols.currentPosition = (playListItem.StartMin*60) + playListItem.StartSec;
                }

                //Don't split the audio out if this is the default screen or it's not a compatable item.
                if (playListItem.SupportsMultiCast && !playListItem.Screen.DefaultScreen)
                {
                    //This code allows us to play the audio via any device we choose, we just need to know the device ID.
                    var waveReader = new MediaFoundationReader(playListItem.FilePath);
                    _waveOut = new WaveOut {DeviceNumber = PlayListItem.Screen.AudioDevice.Id};
                    _waveOut.Init(waveReader);
                    wmPlayer.settings.volume = 0;
                    wmPlayer.URL = playListItem.FilePath;
                    _waveOut.Play();
                }
                else
                {
                    wmPlayer.URL = playListItem.FilePath;
                }
            }
            else if (_currentlyPlayListItem.Type == PlayListItemType.Pdf)
            {
                //NOTE: See the comment in the InitializeComponent() method (where this code should actually be!)
                this.Controls.Add(this.axReader);

                axReader.LoadFile(playListItem.FilePath);
                axReader.setView(playListItem.PdfView);
                axReader.setShowScrollbars(false);
                axReader.setShowToolbar(false);
                axReader.setCurrentPage(playListItem.PdfPageNumber);
                _axReaderCurrentPage = playListItem.PdfPageNumber;

                //Get total number of pages for use in the navigation properties.
                var pdfReader = new PdfReader(playListItem.FilePath);
                _axReaderTotalPages = pdfReader.NumberOfPages;

                //This is madness. The PDF won't actually show unless the form is resized.
                //Tried a refresh but didn't help. This causes a slight flicker but it's the best I can do for now.
                var currentWindowState = WindowState;
                WindowState = FormWindowState.Minimized;
                WindowState = currentWindowState;
            }
            else if (_currentlyPlayListItem.Type == PlayListItemType.Image)
            {
                pbMain.Image = Image.FromFile(playListItem.FilePath);
                pbMain.Visible = true;
                pbMain.SizeMode = PictureBoxSizeMode.Zoom;
                //pbMain.SizeMode  
            }
        }
 /// <summary>
 /// Validates downloaded video file
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 private bool TryOpenInputFile(string file)
 {
     bool isValid = false;
     try
     {
         using (var reader = new MediaFoundationReader(file))
         {
             inputWaveFormat = reader.WaveFormat;
             isValid = true;
         }
     }
     catch (Exception e)
     {
         DialogService.ShowMessageBox(String.Format("The video is not in a supported format. ({0})", e.Message));
     }
     return isValid;
 }
        /// <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);
        }
        private void Resample()
        {
            if (String.IsNullOrEmpty(InputFile))
            {
                MessageBox.Show("Select a file first");
                return;
            }
            var saveFile = SelectSaveFile("resampled");
            if (saveFile == null)
            {
                return;
            }

            // do the resample
            using (var reader = new MediaFoundationReader(InputFile))
            using (var resampler = new MediaFoundationResampler(reader, CreateOutputFormat(reader.WaveFormat)))
            {
                WaveFileWriter.CreateWaveFile(saveFile, resampler);
            }
            MessageBox.Show("Resample complete");
        }
        private void RepositionTest()
        {
            if (String.IsNullOrEmpty(InputFile))
            {
                MessageBox.Show("Select a file first");
                return;
            }
            var saveFile = SelectSaveFile("reposition");
            if (saveFile == null)
            {
                return;
            }
            // do the resample
            using (var reader = new MediaFoundationReader(InputFile))
            using (var resampler = new MediaFoundationResampler(reader, CreateOutputFormat(reader.WaveFormat)))
            {
                CreateRepositionTestFile(saveFile, resampler, () =>
                                                        {
                                                            // tell the reader to go back to the start (we're trusting it not to have leftovers)
                                                            reader.Position = 0;
                                                            // tell the resampler that we have repositioned and it should drain all its buffers
                                                            resampler.Reposition();
                                                        });
            }

            // use the following to test that just the reader is doing clean repositions:
            /*
            using (var reader = new MediaFoundationReader(InputFile))
            {
                CreateRepositionTestFile(saveFile, reader, () =>
                                                        {
                                                            // tell the reader to go back to the start (we're trusting it not to have leftovers)
                                                            reader.Position = 0;
                                                        });
            }*/

            MessageBox.Show("Resample complete");
        }