2017-10-04 264 views
0

我正在使用MediaElement播放視頻。現在我想在播放它之前得到它的總持續時間。這怎麼可能?如何使用UWP的MediaElement獲取視頻的總時長

FileOpenPicker openPicker = new FileOpenPicker(); 
foreach (string extension in FileExtensions.Video) 
{ 
    openPicker.FileTypeFilter.Add(extension); 
} 
StorageFile file = await openPicker.PickSingleFileAsync(); 
// mediaPlayer is a MediaElement defined in XAML 
if (file != null) 
{ 
    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); 
    videoMediaElement.SetSource(stream, file.ContentType); 

    var totalDurationTime = videoMediaElement.NaturalDuration.TimeSpan.TotalSeconds;//get value zero 
    var totalDurationTime1 = TimeSpan.FromSeconds(videoMediaElement.NaturalDuration.TimeSpan.TotalSeconds);//get zero 
    videoMediaElement.Play(); 
} 
+1

也許您需要等待MediaOpened事件,然後檢查文件加載後的長度。根據示例[這裏](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.mediaelement#Windows_UI_Xaml_Controls_MediaElement_MediaOpened)至少對於直播流來說,其他值爲0的值是設置,所以我假設在一個本地文件的情況下,它的長度也應該在該事件之後設置 – Hannes

回答

1

正如@Hannes說,如果你想通過MediaElement類的NaturalDuration屬性來獲得媒體持續時間,你需要把上面的代碼片段裏面MediaOpened事件句柄,例如:

<MediaElement x:Name="videoMediaElement" MediaOpened="videoMediaElement_MediaOpened"></MediaElement> 

private void videoMediaElement_MediaOpened(object sender, RoutedEventArgs e) 
{ 
    var totalDurationTime = videoMediaElement.NaturalDuration.TimeSpan.TotalSeconds; 
    var totalDurationTime1 = TimeSpan.FromSeconds(videoMediaElement.NaturalDuration.TimeSpan.TotalSeconds); 
} 

實際上,您可以通過文件VideoProperties獲取視頻文件的持續時間。甚至可以在打開文件之前獲得持續時間。

StorageFile file = await openPicker.PickSingleFileAsync(); 
Windows.Storage.FileProperties.VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync(); 
Duration videoDuration = videoProperties.Duration; 
0
在XAML中使用

<TextBox x:Name="startTime" Width="20" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" BorderThickness="1" InputScope="Number" /> 

<TextBox x:Name="endTime" Width="20" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,630,135" BorderThickness="1" InputScope="Number"/> 
在xaml.cs

然後文件

long x = Int64.Parse(startTime.Text); 
long y = Int64.Parse(endTime.Text); 


var clip = await MediaClip.CreateFromFileAsync(pickedFile); 
clip.TrimTimeFromStart = new TimeSpan(x * 10000000); 
clip.TrimTimeFromStart = new TimeSpan(y * 10000000); 


composition = new MediaComposition(); 
composition.Clips.Add(clip); 
mediaElement.Position = TimeSpan.Zero; 
mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight); 
mediaElement.SetMediaStreamSource(mediaStreamSource); 

你西港島線通過使用下面的代碼獲得總時長:clip.OriginalDuration.TotalSeconds

相關問題