Пример #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);
        }
Пример #2
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");
            }));
        }
Пример #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("操作成功");
        }
Пример #4
0
 public void Convert(string filePath)
 {
     using (var reader = new MediaFoundationReader(filePath))
     {
         MediaFoundationEncoder.EncodeToMp3(reader, GetNextFileName("convert", ".mp3"));
     }
 }
Пример #5
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();
        }
Пример #6
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);
        }
 /// <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);
     }
 }
Пример #8
0
        internal static void RecordToWma(string fileName)
        {
            using (var wasapiCapture = new WasapiLoopbackCapture())
            {
                wasapiCapture.Initialize();
                var wasapiCaptureSource = new SoundInSource(wasapiCapture);
                using (var stereoSource = wasapiCaptureSource.ToStereo())
                {
                    using (var writer = MediaFoundationEncoder.CreateWMAEncoder(stereoSource.WaveFormat, fileName))
                    {
                        byte[] buffer = new byte[stereoSource.WaveFormat.BytesPerSecond];
                        wasapiCaptureSource.DataAvailable += (s, e) =>
                        {
                            int read = stereoSource.Read(buffer, 0, buffer.Length);
                            writer.Write(buffer, 0, read);
                            Console.Write(".");
                        };

                        wasapiCapture.Start();

                        Console.ReadKey();

                        wasapiCapture.Stop();
                    }
                }
            }
        }
Пример #9
0
 public static void WavToMp4(string relativePath)
 {
     using (var reader = new MediaFoundationReader($"{BotTools.BasePath}\\{relativePath}.wav"))
     {
         MediaFoundationEncoder.EncodeToAac(reader, $"{BotTools.BasePath}\\{relativePath}.mp4");
     }
 }
Пример #10
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);
                    }
                }
            }
        }
Пример #11
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>
        /// 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();
            }
        }
        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);
                }
            }
        }
Пример #14
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);
            }
        }
Пример #15
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);
            }
        }
Пример #16
0
        protected override void OnOpen()
        {
            _validated = Context.QueryString["token"] == _token;
            if (!_validated)
            {
                Context.WebSocket.Close(4000);
            }
            _capture = new WasapiLoopbackCapture(0, new WaveFormat());
            _capture.Initialize();
            _capture.Start();
            var wsStream = new WebSocketStream(this);

            Console.WriteLine($"Captured audio format: {_capture.WaveFormat}");
            IWriteable encoder = null;

            switch (_format)
            {
            case AudioFormat.AAC:
                encoder = new AacEncoder(_capture.WaveFormat, wsStream, 128000,
                                         TranscodeContainerTypes.MFTranscodeContainerType_ADTS);
                break;

            case AudioFormat.MP3:
                encoder = MediaFoundationEncoder.CreateMP3Encoder(_capture.WaveFormat, wsStream, 320000);
                break;
            }

            _capture.DataAvailable += (sender, e) => { encoder?.Write(e.Data, e.Offset, e.ByteCount); };
        }
Пример #17
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);
            }
        }
Пример #18
0
        /// <summary>
        /// Create a new file based on the given filename and start recording to it.
        /// Filename must include its full path.
        /// </summary>
        /// <param name="fileName">The name of a file to be created. Include its full path</param>
        /// <param name="codec">The codec to record in</param>
        /// <param name="bitRate">The bitrate of the file</param>
        /// <param name="channels">The channels to record</param>
        public void StartCapture(string fileName, AvailableCodecs codec, int bitRate, Channels channels)
        {
            if (!ReadyToRecord())
            {
                throw new NullReferenceException("There is no SoundInSource configured for the recorder.");
            }

            fileName = $"{fileName}.{codec.ToString().ToLower()}";

            WaveFormat waveSource;

            switch (channels)
            {
            case Channels.Mono:
                waveSource = _soundInSource.ToMono().WaveFormat;
                break;

            case Channels.Stereo:
                waveSource = _soundInSource.ToStereo().WaveFormat;
                break;

            default:
                throw new ArgumentException("The selected channel option could not be found.");
            }

            switch (codec)
            {
            case AvailableCodecs.MP3:
                _writer = MediaFoundationEncoder.CreateMP3Encoder(waveSource, fileName, bitRate);
                break;

            case AvailableCodecs.AAC:
                _writer = MediaFoundationEncoder.CreateAACEncoder(waveSource, fileName, bitRate);
                break;

            case AvailableCodecs.WMA:
                _writer = MediaFoundationEncoder.CreateWMAEncoder(waveSource, fileName, bitRate);
                break;

            case AvailableCodecs.WAV:
                _writer = new WaveWriter(fileName, waveSource);
                break;

            default:
                throw new ArgumentException("The specified codec was not found.");
            }

            byte[] buffer = new byte[waveSource.BytesPerSecond];

            _soundInSource.DataAvailable += (s, e) =>
            {
                int read = _waveStream.Read(buffer, 0, buffer.Length);
                _writer.Write(buffer, 0, read);
            };

            // Start recording
            _soundInSource.SoundIn.Start();
            _state = RecordingState.Recording;
        }
        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;
            }
        }
 /// <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);
     }
 }
Пример #21
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);
        }
Пример #22
0
 public static MediaType SelectMediaType(Guid audioSubtype, WaveFormat inputFormat, int desiredBitRate)
 {
     return(MediaFoundationEncoder.GetOutputMediaTypes(audioSubtype)
            .Where(mt => mt.SampleRate >= inputFormat.SampleRate && mt.ChannelCount == inputFormat.Channels)
            .Select(mt => new { MediaType = mt, Delta = Math.Abs(desiredBitRate - mt.AverageBytesPerSecond * 8) })
            .OrderBy(mt => mt.Delta)
            .Select(mt => mt.MediaType)
            .FirstOrDefault());
 }
Пример #23
0
        public HttpResponseMessage MakeCoolTrack([FromForm] KaraokeElems value)
        {
            string name = value.TrackName;
            // Getting Image
            var image = value.VoiceFile;

            try
            {
                var voiceFile = "Assets/Yours/" + image.FileName.Substring(0, image.FileName.Length - 4) +
                                "-your-voice.mp3";
                var instFile = "Assets/Nirvana Smells Like Teen Spirit Inst.mp3";

                var trackFile = "Assets/Yours/" + image.FileName.Substring(0, image.FileName.Length - 4) +
                                "-your-track.mp3";

                // Saving Image on Server
                if (image.Length > 0)
                {
                    using (var fileStream = new FileStream(voiceFile, FileMode.Create))
                    {
                        image.CopyTo(fileStream);
                    }
                }

                var voiceWaveSource = CodecFactory.Instance.GetCodec(voiceFile);
                var instWaveSource  = CodecFactory.Instance.GetCodec(instFile);

                using (var cAurio = new AudioControler())
                {
                    VolumeSource vol1, vol2;
                    var          yourTrack = cAurio.MixAudioAndVoice(instWaveSource, out vol1, voiceWaveSource, out vol2);

                    vol1.Volume = 0.5f;
                    vol2.Volume = 0.5f;

                    using (var encoder = MediaFoundationEncoder.CreateMP3Encoder(yourTrack.WaveFormat, trackFile))
                    {
                        byte[] buffer = new byte[yourTrack.WaveFormat.BytesPerSecond];
                        int    read;
                        while ((read = yourTrack.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            encoder.Write(buffer, 0, read);

                            //Console.CursorLeft = 0;
                            //Console.Write("{0:P}/{1:P}", (double) yourTrack.Position / yourTrack.Length, 1);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Пример #24
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")));
                }
            });
        }
Пример #25
0
 public static void ToAudioAgain(string base64Chunks, string outputFile, WaveFormat wav)
 {
     using (var encoder = MediaFoundationEncoder.CreateMP3Encoder(wav, outputFile))
     {
         foreach (var element in base64Chunks.GetByteChunks())
         {
             encoder.Write(element, 0, element.Length);
         }
     }
 }
Пример #26
0
 public void Encode(Stream source, string outputPath, SongTags tags, byte[] reusedBuffer)
 {
     using (var reader = new WaveFileReader(source))
     {
         MediaFoundationEncoder.EncodeToAac(
             reader,
             outputPath
             );
     }
 }
Пример #27
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!");
 }
 public void CanEncodeToMP3()
 {
     using (var source = GlobalTestConfig.TestWav2S())
     {
         using (var encoder = MediaFoundationEncoder.CreateMP3Encoder(source.WaveFormat, _targetfilename))
         {
             MediaFoundationEncoder.EncodeWholeSource(encoder, source);
         }
     }
 }
Пример #29
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);
        }
Пример #30
0
        private void WAVtoMP4()
        {
            sw.Reset();
            sw.Start();
            string plik;

            do
            {
                do
                {
                    plik = textBox1.Text;
                }while (!System.IO.File.Exists(plik));
            }while (!plik.EndsWith(".wav"));
            string plikwav     = plik.Replace(".wav", ".mp4");
            string pliksciezka = plikwav;

            int    index    = plikwav.LastIndexOf("\\");
            string nazwawav = plikwav.Substring(index + 1, plikwav.Length - index - 1);

            index = plik.LastIndexOf("\\");
            string nazwamp3 = plik.Substring(index + 1, plik.Length - index - 1);

            using (var reader = new MediaFoundationReader(textBox1.Text))
            {
                MediaFoundationEncoder.EncodeToAac(reader, plikwav);
            }

            string path1 = Path.GetFileName(plikwav);

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(path1);
            if (fileInfo.Exists)
            {
                long   bytes     = 0;
                double kilobytes = 0;
                double megabytes = 0;

                bytes       = fileInfo.Length;
                kilobytes   = (double)bytes / 1024;
                megabytes   = kilobytes / 1024;
                y           = megabytes;
                label3.Text = "Po konwersji: " + Convert.ToString(Math.Round(megabytes, 3)) + " MB";
                string format1 = fileInfo.Extension;
                label4.Text = Path.GetFileNameWithoutExtension(path1) + "  Typ pliku: " + format1;

                z            = 100 - (y / x) * 100;
                wynik        = Convert.ToInt32(System.Math.Floor(z));
                label11.Text = "Stopień konwersji: " + wynik + "%";
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;

            czas.Text = String.Format("{0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
            MessageBox.Show("Konwersja zakończona. Plik zapisany w: " + plikwav + ".\nNaciśnij dowolny klawisz.");
            Console.In.ReadLine();
        }