2017-10-04 268 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

相关问题