Reputation: 907
I'am playing a video using MediaElement. Now I want to get it's total duration before playing it. How is it possible?
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();
}
Upvotes: 0
Views: 4737
Reputation: 434
in xaml use
<TextBox x:Name="startTime" Width="20" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" BorderThickness="1" InputScope="Number" />
and
<TextBox x:Name="endTime" Width="20" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,630,135" BorderThickness="1" InputScope="Number"/>
then in xaml.cs file
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);
you wil get total duration by using the following code : clip.OriginalDuration.TotalSeconds
Upvotes: 0
Reputation: 10627
As @Hannes said, if you want to get the media duration by NaturalDuration
property of MediaElement
class, you need to put the above code snippet inside MediaOpened
event handle, for example:
<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);
}
Actually, you can get the duration of the video file through the file VideoProperties
. You can get the duration even before you opened the file.
StorageFile file = await openPicker.PickSingleFileAsync();
Windows.Storage.FileProperties.VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();
Duration videoDuration = videoProperties.Duration;
Upvotes: 4