private async Task SetTranscoder(StorageFile source, StorageFile destination, MediaEncodingProfile mediaEncodingProfile, CancellationToken cancellationToken) { MediaTranscoder mediaTranscoder = new MediaTranscoder(); mediaTranscoder.AlwaysReencode = true; CancelTask(cancellationToken); PrepareTranscodeResult prepareTranscodeResult = await mediaTranscoder.PrepareFileTranscodeAsync(source, destination, mediaEncodingProfile); IAsyncActionWithProgress <double> progress = prepareTranscodeResult.TranscodeAsync(); progress.Progress = new AsyncActionProgressHandler <double>(async(progressInfo, info) => { if (cancellationToken.IsCancellationRequested) { progressInfo.Cancel(); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { ReportProgress(Stage7, Stage6ProgressBar, TextProgress6, info); if (info == 100) { Save.Content = "Convert/Save"; } })); }); CancelTask(cancellationToken); }
//</SnippetRun> //<SnippetTranscodeFileAsync> private async Task TranscodeFileAsync() { transcoder = new MediaTranscoder(); try { var settings = ApplicationData.Current.LocalSettings; settings.Values["TranscodingStatus"] = "Started"; var inputFileName = ApplicationData.Current.LocalSettings.Values["InputFileName"] as string; var outputFileName = ApplicationData.Current.LocalSettings.Values["OutputFileName"] as string; if (inputFileName == null || outputFileName == null) { return; } // retrieve the transcoding information var inputFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(inputFileName); var outputFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(outputFileName); // create video encoding profile MediaEncodingProfile encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); Debug.WriteLine("PrepareFileTranscodeAsync"); settings.Values["TranscodingStatus"] = "Preparing to transcode "; PrepareTranscodeResult preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync( inputFile, outputFile, encodingProfile); if (preparedTranscodeResult.CanTranscode) { var startTime = TimeSpan.FromMilliseconds(DateTime.Now.Millisecond); Debug.WriteLine("Starting transcoding @" + startTime); var progress = new Progress <double>(TranscodeProgress); settings.Values["TranscodingStatus"] = "Transcoding "; settings.Values["ProcessingFileName"] = inputFileName; await preparedTranscodeResult.TranscodeAsync().AsTask(cancelTokenSource.Token, progress); } else { Debug.WriteLine("Source content could not be transcoded."); Debug.WriteLine("Transcode status: " + preparedTranscodeResult.FailureReason.ToString()); var endTime = TimeSpan.FromMilliseconds(DateTime.Now.Millisecond); Debug.WriteLine("End time = " + endTime); } } catch (Exception e) { Debug.WriteLine("Exception type: {0}", e.ToString()); throw; } }
public async void PickMedia() { var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; openPicker.FileTypeFilter.Add(".wmv"); openPicker.FileTypeFilter.Add(".mp4"); StorageFile source = await openPicker.PickSingleFileAsync(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; savePicker.DefaultFileExtension = ".mp3"; savePicker.SuggestedFileName = "New Video"; savePicker.FileTypeChoices.Add("MPEG3", new string[] { ".mp3" }); StorageFile destination = await savePicker.PickSaveFileAsync(); MediaEncodingProfile profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(source, destination, profile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += new AsyncActionProgressHandler <double>(TranscodeProgress); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>(TranscodeComplete); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: System.Diagnostics.Debug.WriteLine("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: System.Diagnostics.Debug.WriteLine("Invalid profile."); break; default: System.Diagnostics.Debug.WriteLine("Unknown failure."); break; } } }
public async Task <IAsyncActionWithProgress <double> > StartTranscodeMedia(StorageFile inputFile, StorageFile outFile, MediaEncodingProfile profile) { MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(inputFile, outFile, profile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += new AsyncActionProgressHandler <double>((asyncInfo, e) => { ProcessingProgressChanged?.Invoke(this, e); }); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>((asyncInfo, status) => { asyncInfo.GetResults(); switch (status) { case AsyncStatus.Canceled: ProcessingCanceled?.Invoke(this, new EventArgs()); break; case AsyncStatus.Completed: ProcessingCompleted?.Invoke(this, new EventArgs()); break; case AsyncStatus.Started: break; case AsyncStatus.Error: default: ProcessingError?.Invoke(this, "转码失败"); break; } }); return(transcodeOp); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: ProcessingError?.Invoke(this, "转码失败:找不到编解码器"); break; case TranscodeFailureReason.InvalidProfile: ProcessingError?.Invoke(this, "转码失败:配置文件无效"); break; default: ProcessingError?.Invoke(this, "转码失败:未知错误"); break; } return(null); } }
public async Task InitStartTranscoder() { if (parent != null) { parent.StartWritingOutput("Initialize Transcoder", 1); } tempFile = await GetTempOutputFile(); if (parent != null) { parent.StartWritingOutputExtended("Temporary Output : " + tempFile.Path, 0); } IRandomAccessStream destStream = await tempFile.OpenAsync(FileAccessMode.ReadWrite); int width = 320; int height = 200; if (gcitem != null) { width = gcitem.Size.Width; height = gcitem.Size.Height; } frameCounter = 0; Timestamp = TimeSpan.Zero; VideoEncodingProperties videoSourceProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Rgb32, (uint)width, (uint)height); VideoStreamDescriptor videoSourceDescriptor = new VideoStreamDescriptor(videoSourceProperties); MediaStreamSource mediaStreamSource = new MediaStreamSource(videoSourceDescriptor); mediaStreamSource.BufferTime = TimeSpan.FromSeconds(0); mediaStreamSource.Starting += OnMSSStarting; mediaStreamSource.SampleRequested += OnMSSSampleRequested; mediaStreamSource.SampleRendered += OnMSSSampleRendered; //mediaStreamSource.CanSeek = false; MediaTranscoder mediaTranscoder = new MediaTranscoder(); mediaTranscoder.HardwareAccelerationEnabled = true; //////////////////// //Start Transcoding MediaEncodingProfile destProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); PrepareTranscodeResult transcodeOperation = await mediaTranscoder.PrepareMediaStreamSourceTranscodeAsync(mediaStreamSource, destStream, destProfile); //await transcode.TranscodeAsync(); var rendering = transcodeOperation.TranscodeAsync(); rendering.Progress += progressHandler; rendering.Completed += completedHandler; }
private async void TranscodeWithEffect() { var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; openPicker.FileTypeFilter.Add(".wmv"); openPicker.FileTypeFilter.Add(".mp4"); StorageFile sourceFile = await openPicker.PickSingleFileAsync(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; savePicker.DefaultFileExtension = ".mp4"; savePicker.SuggestedFileName = "New Video"; savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".mp4" }); StorageFile destinationFile = await savePicker.PickSaveFileAsync(); MediaEncodingProfile mediaEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); //<SnippetTrancodeWithEffect> MediaTranscoder transcoder = new MediaTranscoder(); // Using the in-box video stabilization effect works //VideoStabilizationEffectDefinition videoEffect = new VideoStabilizationEffectDefinition(); //transcoder.AddVideoEffect(videoEffect.ActivatableClassId); // My custom effect throws an exception var customEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect", new PropertySet() { { "FadeValue", .25 } }); transcoder.AddVideoEffect(customEffectDefinition.ActivatableClassId); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(sourceFile, destinationFile, mediaEncodingProfile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); } //</SnippetTrancodeWithEffect> }
/// <summary> /// Return true if audio can be transcoded /// </summary> /// <returns></returns> public async Task <bool> ConvertAudioAsync() { PrepareTranscode = await this.TransCoder.PrepareFileTranscodeAsync(this.SourceAudio, this.DestinationAudio, profile); if (PrepareTranscode.CanTranscode) { var transcodeOp = PrepareTranscode.TranscodeAsync(); return(true); } else { return(false); } }
public async Task CS_W_MT_Basic(EffectType effectType) { StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4")); StorageFile destination = await CreateDestinationFileAync("CS_W_MT_Basic_" + effectType + ".mp4"); var definition = await Utils.CreateEffectDefinitionAsync(effectType); var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); PrepareTranscodeResult transcode = await transcoder.PrepareFileTranscodeAsync(source, destination, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga)); await transcode.TranscodeAsync(); }
public async Task <StorageFile> ConvertToMP3() { bool SuccessFlag = true; try { StorageFolder folder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync("Conversion", CreationCollisionOption.OpenIfExists); StorageFile destinationFile = await folder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName); if (SuccessFlag) { mediatranscoder = new MediaTranscoder(); PrepareTranscodeResult transcoderesult = await mediatranscoder.PrepareFileTranscodeAsync(file, destinationFile, isM4A?MediaEncodingProfile.CreateM4a(quality) : MediaEncodingProfile.CreateMp3(quality)); if (transcoderesult.CanTranscode) { canceltoken = new CancellationToken(); await transcoderesult.TranscodeAsync(); SuccessFlag = true; } else { SuccessFlag = false; } } if (SuccessFlag) { return(destinationFile); } else { return(null); } } catch (Exception ee) { Debug.WriteLine(ee.ToString()); } return(null); }
public async Task CS_W_MT_LumiaCropSquare(String inputFileName, String outputFileName) { StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/" + inputFileName)); StorageFile destination = await CreateDestinationFileAync(outputFileName); // Select the largest centered square area in the input video var encodingProfile = await TranscodingProfile.CreateFromFileAsync(source); uint inputWidth = encodingProfile.Video.Width; uint inputHeight = encodingProfile.Video.Height; uint outputLength = Math.Min(inputWidth, inputHeight); Rect cropArea = new Rect( (float)((inputWidth - outputLength) / 2), (float)((inputHeight - outputLength) / 2), (float)outputLength, (float)outputLength ); encodingProfile.Video.Width = outputLength; encodingProfile.Video.Height = outputLength; var definition = new LumiaEffectDefinition(new FilterChainFactory(() => { var filters = new List <IFilter>(); filters.Add(new CropFilter(cropArea)); return(filters); })); definition.InputWidth = inputWidth; definition.InputHeight = inputHeight; definition.OutputWidth = outputLength; definition.OutputHeight = outputLength; var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); PrepareTranscodeResult transcode = await transcoder.PrepareFileTranscodeAsync(source, destination, encodingProfile); await transcode.TranscodeAsync(); }
private async void Transcode_Click(object sender, RoutedEventArgs e) { StartMediaTranscoder.IsEnabled = false; StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Car.mp4")); StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectsTestApp.MediaTranscoder.mp4", CreationCollisionOption.ReplaceExisting); var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); var definition = await CreateEffectDefinitionAsync(encodingProfile.Video); var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); PrepareTranscodeResult transcode = await transcoder.PrepareFileTranscodeAsync(source, destination, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga)); await transcode.TranscodeAsync(); StartMediaTranscoder.IsEnabled = true; }
private async void OnTransCode(object sender, RoutedEventArgs e) { Button btn = sender as Button; btn.IsEnabled = false; // 從專案目錄中取得待轉碼的MP3檔案 Uri sourceFileUri = new Uri("ms-appx:///1.mp3"); StorageFile srcFile = await StorageFile.GetFileFromApplicationUriAsync(sourceFileUri); // 取得“音樂”檔案目錄 StorageFolder musicFd = KnownFolders.MusicLibrary; // 新檔名 string newFileName = "new_file.m4a"; // 建立新檔案 StorageFile disFile = await musicFd.CreateFileAsync(newFileName, CreationCollisionOption.ReplaceExisting); // 響應轉碼處理進度 IProgress <double> progress = new Progress <double>((p) => { // 更新進度 this.pb.Value = p; }); // 案例化MediaTranscoder物件 MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult result = await transcoder.PrepareFileTranscodeAsync(srcFile, disFile, MediaEncodingProfile.CreateM4a(AudioEncodingQuality.High)); // 開始轉碼 if (result.CanTranscode) { await result.TranscodeAsync().AsTask(progress); } btn.IsEnabled = true; }
/// <summary> /// 提供音视频转码 /// </summary> /// <param name="SourceFile">源文件</param> /// <param name="DestinationFile">目标文件</param> /// <param name="MediaTranscodeEncodingProfile">转码编码</param> /// <param name="MediaTranscodeQuality">转码质量</param> /// <param name="SpeedUp">是否启用硬件加速</param> /// <returns></returns> public static Task TranscodeFromAudioOrVideoAsync(StorageFile SourceFile, StorageFile DestinationFile, string MediaTranscodeEncodingProfile, string MediaTranscodeQuality, bool SpeedUp) { return Task.Factory.StartNew((ob) => { IsAnyTransformTaskRunning = true; AVTranscodeCancellation = new CancellationTokenSource(); var Para = (ValueTuple<StorageFile, StorageFile, string, string, bool>)ob; MediaTranscoder Transcoder = new MediaTranscoder { HardwareAccelerationEnabled = true, VideoProcessingAlgorithm = Para.Item5 ? MediaVideoProcessingAlgorithm.Default : MediaVideoProcessingAlgorithm.MrfCrf444 }; try { MediaEncodingProfile Profile = null; VideoEncodingQuality VideoQuality = default; AudioEncodingQuality AudioQuality = default; switch (Para.Item4) { case "UHD2160p": VideoQuality = VideoEncodingQuality.Uhd2160p; break; case "QVGA": VideoQuality = VideoEncodingQuality.Qvga; break; case "HD1080p": VideoQuality = VideoEncodingQuality.HD1080p; break; case "HD720p": VideoQuality = VideoEncodingQuality.HD720p; break; case "WVGA": VideoQuality = VideoEncodingQuality.Wvga; break; case "VGA": VideoQuality = VideoEncodingQuality.Vga; break; case "High": AudioQuality = AudioEncodingQuality.High; break; case "Medium": AudioQuality = AudioEncodingQuality.Medium; break; case "Low": AudioQuality = AudioEncodingQuality.Low; break; } switch (Para.Item3) { case "MKV": Profile = MediaEncodingProfile.CreateHevc(VideoQuality); break; case "MP4": Profile = MediaEncodingProfile.CreateMp4(VideoQuality); break; case "WMV": Profile = MediaEncodingProfile.CreateWmv(VideoQuality); break; case "AVI": Profile = MediaEncodingProfile.CreateAvi(VideoQuality); break; case "MP3": Profile = MediaEncodingProfile.CreateMp3(AudioQuality); break; case "ALAC": Profile = MediaEncodingProfile.CreateAlac(AudioQuality); break; case "WMA": Profile = MediaEncodingProfile.CreateWma(AudioQuality); break; case "M4A": Profile = MediaEncodingProfile.CreateM4a(AudioQuality); break; } PrepareTranscodeResult Result = Transcoder.PrepareFileTranscodeAsync(Para.Item1, Para.Item2, Profile).AsTask().Result; if (Result.CanTranscode) { SendUpdatableToastWithProgressForTranscode(Para.Item1, Para.Item2); Progress<double> TranscodeProgress = new Progress<double>((CurrentValue) => { NotificationData Data = new NotificationData(); Data.SequenceNumber = 0; Data.Values["ProgressValue"] = (Math.Ceiling(CurrentValue) / 100).ToString(); Data.Values["ProgressValueString"] = Convert.ToInt32(CurrentValue) + "%"; ToastNotificationManager.CreateToastNotifier().Update(Data, "TranscodeNotification"); }); Result.TranscodeAsync().AsTask(AVTranscodeCancellation.Token, TranscodeProgress).Wait(); ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "Success"; } else { ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "NotSupport"; Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } } catch (AggregateException) { ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "Cancel"; Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } catch (Exception e) { ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = e.Message; Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } }, (SourceFile, DestinationFile, MediaTranscodeEncodingProfile, MediaTranscodeQuality, SpeedUp), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Current).ContinueWith((task, ob) => { AVTranscodeCancellation.Dispose(); AVTranscodeCancellation = null; var Para = (ValueTuple<StorageFile, StorageFile>)ob; if (ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] is string ExcuteStatus) { CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { switch (ExcuteStatus) { case "Success": TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Success"), 5000); ShowTranscodeCompleteNotification(Para.Item1, Para.Item2); break; case "Cancel": TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Cancel"), 5000); ShowTranscodeCancelNotification(); break; case "NotSupport": TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_NotSupport"), 5000); break; default: TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Failure") + ExcuteStatus, 5000); break; } }).AsTask().Wait(); } IsAnyTransformTaskRunning = false; }, (SourceFile, DestinationFile), TaskScheduler.Current); }
/// <summary> /// Converts the chosen media to a certain extension the user has chosen for /// </summary> /// <param name="selectedFiles"></param> /// <param name="output"></param> public async void ConvertChosenMedia(List <StorageFile> selectedFiles, string output) { List <StorageFile> files = selectedFiles; foreach (StorageFile file in files) { StorageFile source = file; MediaEncodingProfile profile = new MediaEncodingProfile(); var ext = file.FileType; //To which extension needs the file be converted to switch (output) { case "MP3": if (ext == ".MP3") { ext = null; MessageDialog showDialogError = new MessageDialog("Het bestand kan niet naar dezelfde extensie geconverteerd worden."); await showDialogError.ShowAsync(); } else { profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); } break; case "MP4": if (ext == ".MP4") { ext = null; MessageDialog showDialogError = new MessageDialog("Het bestand kan niet naar dezelfde extensie geconverteerd worden."); await showDialogError.ShowAsync(); } else { profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); } break; case "WAV": if (ext == ".WAV") { ext = null; MessageDialog showDialogError = new MessageDialog("Het bestand kan niet naar dezelfde extensie geconverteerd worden."); await showDialogError.ShowAsync(); } profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); break; default: output = null; MessageDialog showDialogUnknown = new MessageDialog("Gekozen formaat om naar te converten is niet geldig."); await showDialogUnknown.ShowAsync(); break; } //Puts the file in the "Video's" folder if (output != null && ext != null) { var folder = KnownFolders.VideosLibrary; string datetime = "_" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; var destination = await folder.CreateFileAsync(source.Name.Remove(source.Name.Length - 4) + datetime + "." + output); MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = null; while (source.Equals(null) || destination.Equals(null) || profile.Equals(null)) { //waiting } using (await bouncer.LockAsync()) { //catch the nullreference exception on prepareOp try { prepareOp = await transcoder.PrepareFileTranscodeAsync(source, destination, profile); //if possible if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>(TranscodeComplete); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Debug.WriteLine("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: Debug.WriteLine("Invalid profile."); break; default: Debug.WriteLine("Unknown failure."); break; } } } catch (NullReferenceException ex) { Debug.WriteLine(ex.Message); } } } } }
public async void ConvertChosenMedia(List <StorageFile> selectedFiles, string output) { List <StorageFile> files = selectedFiles; foreach (StorageFile file in files) { StorageFile source = file; MediaEncodingProfile profile = new MediaEncodingProfile(); //wat wil de gebruiker er mee switch (output) { case "MP3": profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); break; case "MP4": profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto); break; case "WAV": profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); break; default: Debug.WriteLine("Gekozen formaat om naar te converten staat niet in de switchlijst"); break; } //bepaald waar het nieuwe bestand komt var folder = KnownFolders.VideosLibrary; string datetime = "_" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; var destination = await folder.CreateFileAsync(source.Name.Remove(source.Name.Length - 4) + datetime + "." + output); MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = null; while (source.Equals(null) || destination.Equals(null) || profile.Equals(null)) { //blijf wachten } using (await bouncer.LockAsync()) { //afvangen dat prepareOp nullreferenceexception gooit try { prepareOp = await transcoder.PrepareFileTranscodeAsync(source, destination, profile); //als het kan if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += new AsyncActionProgressHandler <double>(TranscodeProgress); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>(TranscodeComplete); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Debug.WriteLine("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: Debug.WriteLine("Invalid profile."); break; default: Debug.WriteLine("Unknown failure."); break; } } } catch (NullReferenceException ex) { Debug.WriteLine(ex.Message); } } }//foreach }
/// <summary> /// 提供音视频转码 /// </summary> /// <param name="SourceFile">源文件</param> /// <param name="DestinationFile">目标文件</param> /// <param name="MediaTranscodeEncodingProfile">转码编码</param> /// <param name="MediaTranscodeQuality">转码质量</param> /// <param name="SpeedUp">是否启用硬件加速</param> /// <returns></returns> public static Task TranscodeFromAudioOrVideoAsync(StorageFile SourceFile, StorageFile DestinationFile, string MediaTranscodeEncodingProfile, string MediaTranscodeQuality, bool SpeedUp) { return(Task.Factory.StartNew((obj) => { if (obj is ValueTuple <StorageFile, StorageFile, string, string, bool> Para) { using (ExtendedExecutionController ExtExecution = ExtendedExecutionController.TryCreateExtendedExecution().Result) { IsAnyTransformTaskRunning = true; AVTranscodeCancellation = new CancellationTokenSource(); MediaTranscoder Transcoder = new MediaTranscoder { HardwareAccelerationEnabled = true, VideoProcessingAlgorithm = Para.Item5 ? MediaVideoProcessingAlgorithm.Default : MediaVideoProcessingAlgorithm.MrfCrf444 }; try { MediaEncodingProfile Profile = null; VideoEncodingQuality VideoQuality = default; AudioEncodingQuality AudioQuality = default; switch (Para.Item4) { case "UHD2160p": VideoQuality = VideoEncodingQuality.Uhd2160p; break; case "QVGA": VideoQuality = VideoEncodingQuality.Qvga; break; case "HD1080p": VideoQuality = VideoEncodingQuality.HD1080p; break; case "HD720p": VideoQuality = VideoEncodingQuality.HD720p; break; case "WVGA": VideoQuality = VideoEncodingQuality.Wvga; break; case "VGA": VideoQuality = VideoEncodingQuality.Vga; break; case "High": AudioQuality = AudioEncodingQuality.High; break; case "Medium": AudioQuality = AudioEncodingQuality.Medium; break; case "Low": AudioQuality = AudioEncodingQuality.Low; break; } switch (Para.Item3) { case "MKV": Profile = MediaEncodingProfile.CreateHevc(VideoQuality); break; case "MP4": Profile = MediaEncodingProfile.CreateMp4(VideoQuality); break; case "WMV": Profile = MediaEncodingProfile.CreateWmv(VideoQuality); break; case "AVI": Profile = MediaEncodingProfile.CreateAvi(VideoQuality); break; case "MP3": Profile = MediaEncodingProfile.CreateMp3(AudioQuality); break; case "ALAC": Profile = MediaEncodingProfile.CreateAlac(AudioQuality); break; case "WMA": Profile = MediaEncodingProfile.CreateWma(AudioQuality); break; case "M4A": Profile = MediaEncodingProfile.CreateM4a(AudioQuality); break; } PrepareTranscodeResult Result = Transcoder.PrepareFileTranscodeAsync(Para.Item1, Para.Item2, Profile).AsTask().Result; if (Result.CanTranscode) { SendUpdatableToastWithProgressForTranscode(Para.Item1, Para.Item2); Progress <double> TranscodeProgress = new Progress <double>((CurrentValue) => { try { NotificationData Data = new NotificationData { SequenceNumber = 0 }; Data.Values["ProgressValue"] = (Math.Ceiling(CurrentValue) / 100).ToString(); Data.Values["ProgressValueString"] = Convert.ToInt32(CurrentValue) + "%"; ToastNotificationManager.CreateToastNotifier().Update(Data, "TranscodeNotification"); } catch (Exception ex) { LogTracer.Log(ex, "Toast notification could not be sent"); } }); Result.TranscodeAsync().AsTask(AVTranscodeCancellation.Token, TranscodeProgress).Wait(); CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowTranscodeCompleteNotification(Para.Item1, Para.Item2); }).AsTask().Wait(); } else { LogTracer.Log("Transcode format is not supported"); Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } } catch (AggregateException) { Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } catch (Exception ex) { LogTracer.Log(ex, "Transcode failed"); Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait(); } finally { AVTranscodeCancellation.Dispose(); AVTranscodeCancellation = null; IsAnyTransformTaskRunning = false; } } } }, (SourceFile, DestinationFile, MediaTranscodeEncodingProfile, MediaTranscodeQuality, SpeedUp), TaskCreationOptions.LongRunning)); }
private async void Button_Click_1(object sender, RoutedEventArgs e) { //MediaEncodingProfile profile = new MediaEncodingProfile(); //profile.Video = property; //profile.Video.Subtype = MediaEncodingSubtypes.H264; //profile.Video.Height = Source_height; //profile.Video.Width = Source_width; //profile.Video.FrameRate.Numerator = Source_frameRate; //profile.Audio.Subtype = MediaEncodingSubtypes.Aac; //profile.Audio.SampleRate = SampleRate; MediaEncodingProfile profile = await MediaEncodingProfile.CreateFromFileAsync(source); profile.Video.Subtype = MediaEncodingSubtypes.H264; profile.Video.Height = Source_height; profile.Video.Width = Source_width; profile.Video.FrameRate.Numerator = Source_frameRate; profile.Audio.SampleRate = SampleRate; profile.Audio.Subtype = MediaEncodingSubtypes.Aac; MediaTranscoder transcoder = new MediaTranscoder(); //MediaEncodingProfile profile = new MediaEncodingProfile(); //profile.Video.Subtype = MediaEncodingSubtypes.H264; //profile.Video.Height = Source_height; //profile.Video.Width = Source_width; //profile.Video.FrameRate.Numerator = Source_frameRate; //profile.Video.Bitrate = property.Bitrate; //profile.Audio.SampleRate = SampleRate; //profile.Audio.Subtype = MediaEncodingSubtypes.Aac; //MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(source, destination, profile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += new AsyncActionProgressHandler <double>(TranscodeProgress); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>(TranscodeComplete); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: System.Diagnostics.Debug.WriteLine("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: System.Diagnostics.Debug.WriteLine("Invalid profile."); break; default: System.Diagnostics.Debug.WriteLine("Unknown failure."); break; } } }
private async Task TranscodeMediaAsync() { MediaVideoProcessingAlgorithm Algorithm = default; if (ApplicationData.Current.LocalSettings.Values["MediaTranscodeAlgorithm"] is string TranscodeAlgorithm) { if (TranscodeAlgorithm == "MrfCrf444") { Algorithm = MediaVideoProcessingAlgorithm.MrfCrf444; } else if (TranscodeAlgorithm == "Default") { Algorithm = MediaVideoProcessingAlgorithm.Default; } MediaTranscoder Transcoder = new MediaTranscoder { HardwareAccelerationEnabled = true, VideoProcessingAlgorithm = Algorithm }; if (ApplicationData.Current.LocalSettings.Values["MediaTranscodeInputFileToken"] is string InputFileToken && ApplicationData.Current.LocalSettings.Values["MediaTranscodeOutputFileToken"] is string OutputFileToken) { try { var FutureItemAccessList = StorageApplicationPermissions.FutureAccessList; InputFile = await FutureItemAccessList.GetFileAsync(InputFileToken); OutputFile = await FutureItemAccessList.GetFileAsync(OutputFileToken); if (ApplicationData.Current.LocalSettings.Values["MediaTranscodeEncodingProfile"] is string EncodingKind && ApplicationData.Current.LocalSettings.Values["MediaTranscodeQuality"] is string Quality) { MediaEncodingProfile Profile = null; VideoEncodingQuality VideoQuality = default; AudioEncodingQuality AudioQuality = default; switch (Quality) { case "UHD2160p": VideoQuality = VideoEncodingQuality.Uhd2160p; break; case "QVGA": VideoQuality = VideoEncodingQuality.Qvga; break; case "HD1080p": VideoQuality = VideoEncodingQuality.HD1080p; break; case "HD720p": VideoQuality = VideoEncodingQuality.HD720p; break; case "WVGA": VideoQuality = VideoEncodingQuality.Wvga; break; case "VGA": VideoQuality = VideoEncodingQuality.Vga; break; case "High": AudioQuality = AudioEncodingQuality.High; break; case "Medium": AudioQuality = AudioEncodingQuality.Medium; break; case "Low": AudioQuality = AudioEncodingQuality.Low; break; } switch (EncodingKind) { case "MKV": Profile = MediaEncodingProfile.CreateHevc(VideoQuality); break; case "MP4": Profile = MediaEncodingProfile.CreateMp4(VideoQuality); break; case "WMV": Profile = MediaEncodingProfile.CreateWmv(VideoQuality); break; case "AVI": Profile = MediaEncodingProfile.CreateAvi(VideoQuality); break; case "MP3": Profile = MediaEncodingProfile.CreateMp3(AudioQuality); break; case "ALAC": Profile = MediaEncodingProfile.CreateAlac(AudioQuality); break; case "WMA": Profile = MediaEncodingProfile.CreateWma(AudioQuality); break; case "M4A": Profile = MediaEncodingProfile.CreateM4a(AudioQuality); break; } PrepareTranscodeResult Result = await Transcoder.PrepareFileTranscodeAsync(InputFile, OutputFile, Profile); if (Result.CanTranscode) { SendUpdatableToastWithProgress(); Progress <double> TranscodeProgress = new Progress <double>(ProgressHandler); await Result.TranscodeAsync().AsTask(Cancellation.Token, TranscodeProgress); ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "Success"; } else { ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "转码格式不支持"; await OutputFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } } else { ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "SettingError: Miss MediaTranscodeEncodingProfile Or MediaTranscodeQuality"; await OutputFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } }
private async Task Covert_music(string audio, string type) { using (SQLiteConnection db = new SQLiteConnection(App.DB_PATH)) { MediaEncodingProfile profile = new MediaEncodingProfile(); if (type == ".mp3") { var Quality = Load_options(Json.Json_mp3); profile = MediaEncodingProfile.CreateMp3(Quality); } else if (type == ".alac") { var Quality = Load_options(Json.Json_alac); profile = MediaEncodingProfile.CreateAlac(Quality); type = ".m4a"; } else if (type == ".flac") { var Quality = Load_options(Json.Json_flac); profile = MediaEncodingProfile.CreateFlac(Quality); } else if (type == ".aac") { var Quality = Load_options(Json.Json_aac); profile = MediaEncodingProfile.CreateM4a(Quality); type = ".m4a"; } convert_type = type.Substring(1); var songs = db.Query <Song>("Select * from Song"); foreach (var song in songs) { var format = db.Find <MusicFormat>(c => c.Id == song.FormatId); var import_name = song.Path + song.NameSong + "." + format.NameFormat; string new_name = song.Path + song.NameSong + type; Main_folder = await Windows.Storage.AccessCache.StorageApplicationPermissions .FutureAccessList.GetFolderAsync("Audio"); StorageFile oldfile = await Main_folder.GetFileAsync(import_name); MusicProperties musicProperties = await oldfile.Properties.GetMusicPropertiesAsync(); if (oldfile.FileType != ".mp3" && oldfile.FileType != type && musicProperties.Bitrate > 500000) { StorageFile newfile = await Main_folder.CreateFileAsync(new_name, CreationCollisionOption.ReplaceExisting); if (oldfile != null && newfile != null) { try { current_song = song; all_convert_song++; SongDeleteAfterConvert.Add(current_song); MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(oldfile, newfile, profile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Completed += async(IAsyncActionWithProgress <double> asyncInfo, AsyncStatus status) => { asyncInfo.GetResults(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { current_convert_song++; }); }; } } catch (Exception exc) { var dialog = new MessageDialog(exc.ToString()); await dialog.ShowAsync(); } } } } do { await Task.Delay(TimeSpan.FromSeconds(3)); }while (all_convert_song != current_convert_song); Delete_oldfile(); } }