Creating a simple seeking media player with MediaElement in WPF
I have also posted this on MSDN forums - i hope its not a problem.
I am basically trying to create a WPF based video player which allows you to seek within media. I'm trying to implement it using MediaTimeline (i know i can change the Position property, but i had other issues which i'll post in a separate question). XAML and code-behind are below.
Thanks for looking...
MainWindow.xaml
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="WidthAndHeight">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<MediaElement x:Name="mediaElement" Width="320" Height="240" Margin="4" LoadedBehavior="Manual"/>
<Slider x:Name="slider" Grid.Row="1" Margin="4"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
n开发者_开发问答amespace WpfApplication5
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var tl = new MediaTimeline(new Uri(@"c:\temp\!numa.wmv"));
mediaElement.Clock = tl.CreateClock(true) as MediaClock;
mediaElement.MediaOpened += (o, e) =>
{
slider.Maximum = mediaElement.NaturalDuration.TimeSpan.Seconds;
mediaElement.Clock.Controller.Pause();
};
slider.ValueChanged += (o, e) =>
{
mediaElement.Clock.Controller.Seek(TimeSpan.FromSeconds(slider.Value), TimeSeekOrigin.BeginTime);
};
}
}
}
You need to set ScrubbingEnabled="True" on MediaElement to have it update during seeks.
the MediaOpened event should actually be setting the maximum value to .TotalSeconds, and you should also set ScrubbingEnabled to True as jesperll pointed out.
精彩评论