我试图在WPF中创建一个基本的视频播放器。我有一个MediaElement来显示视频和滑块来控制它。
我的问题是,当我设置MediaElement的Position属性时,视频停止播放。
我的xaml:
<UserControl x:Class="vPlayer.Forms.mPlayer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<MediaElement LoadedBehavior="Manual" Name="mePlayer" Margin="0,0,0,45" MediaOpened="mePlayer_MediaOpened" />
<Slider Height="20" Name="Bar" VerticalAlignment="Bottom" Margin="0,0,0,25" MouseLeftButtonUp="Bar_MouseLeftButtonUp"></Slider>
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Bottom">
<Button x:Name="btnPlay" Click="btnPlay_Click" Content="Oynat"/>
<Button x:Name="btnPause" Margin="5,0" Click="btnPause_Click" Content="Duraklat"/>
<Button x:Name="btnStop" Click="btnStop_Click" Content="Durdur"/>
</WrapPanel>
</Grid>
</UserControl>
我的代码的相对部分:
private TimeSpan TotalTime;
DispatcherTimer _timer = new DispatcherTimer();
public mPlayer(string url)
{
InitializeComponent();
mePlayer.Source = new Uri(url);
Bar.AddHandler(MouseLeftButtonUpEvent,
new MouseButtonEventHandler(Bar_MouseLeftButtonUp),
true);
}
void timer_Tick(object sender, EventArgs e)
{
// Check if the movie finished calculate it's total time
if (mePlayer.NaturalDuration.TimeSpan.TotalSeconds > 0)
{
if (TotalTime.TotalSeconds > 0)
{
// Updating time slider
Bar.Value = mePlayer.Position.TotalSeconds /
TotalTime.TotalSeconds;
}
}
}
private void mePlayer_MediaOpened(object sender, RoutedEventArgs e)
{
TotalTime = mePlayer.NaturalDuration.TimeSpan;
// Create a timer that will update the counters and the time slider
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += new EventHandler(timer_Tick);
_timer.Start();
}
private void Bar_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (TotalTime.TotalSeconds > 0)
{
mePlayer.Position = TimeSpan.FromSeconds(Bar.Value * TotalTime.TotalSeconds);
}
}
答案 0 :(得分:1)
您只能在媒体播放后更改位置,订阅活动MediaOpened
。
其次,并非所有媒体都是可搜索的,请使用属性CanSeek
以确定它是否可行。
来源:How to change the position of a video using MediaElement in Windows8?