WPF - 位置更改后,媒体元素停止播放



我正在尝试在WPF中创建一个基本的视频播放器。我有一个媒体元素来显示视频和滑块来控制它。

我的问题是,当我设置MediaElement的位置属性时,视频停止播放。

我的 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);
            }
        }

您只能在打开媒体后更改位置,订阅事件MediaOpened

其次,并非所有媒体都是可搜索的,请使用属性CanSeek以确定它是否可能。

来源:如何在Windows8中使用MediaElement更改视频的位置?

最新更新