c# - 如何在 WPF 中向后播放视频?

标签 c# .net wpf c#-4.0 video

我想在 WPF 中顺畅地向后播放视频。我正在使用 MediaElement 播放视频。我读了this post这建议定期更改 MediaElement.Position 以模仿倒带行为。

我尝试使用以下代码更改 MediaElement.Position 的位置

private void Button_Click(object sender, RoutedEventArgs e)
{
    mePlayer.Pause();                               //Pause the media player first
    double m = 1 / frameRate;                       //Calculate the time for each frame
    double t = 120;                                 //Total length of video in seconds
    mePlayer.Position = TimeSpan.FromMinutes(2);    //Start video from 2 min
    while (t >= 60)                                 //Check if time exceeds 1 min
    {
        t = t - m;                                  //Subtract the single frame time from total seconds
        mePlayer.Position = TimeSpan.FromSeconds(t);//set position of video
    }
}

在上面的代码中,我试图从 2 分钟到 1 分钟向后播放视频。 它在 mePlayer.Position = TimeSpan.FromSeconds(t) 上给我“System.OverflowException”。

如果有人知道如何在 WPF 中向后播放视频,请帮助我实现这种效果。谢谢。

最佳答案

要顺利完成,您应该使用 Timer。假设帧速率为 24 fps,则意味着每 1/24 = 0.0416 秒或大约 42 毫秒为一帧。因此,如果您的计时器每 42 毫秒计时一次,您可以向后移动 mePlayer.Position:

XAML:

<MediaElement x:Name="mePlayer" Source="C:\Sample.mp4"
              LoadedBehavior="Manual" ScrubbingEnabled="True"/>

代码:

    System.Windows.Threading.DispatcherTimer dispatcherTimer;
    int t = 240000; // 4 minutes = 240,000 milliseconds

    public MainWindow()
    {
        InitializeComponent();

        dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        //tick every 42 millisecond = tick 24 times in one second
        dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 42);

    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        // Go back 1 frame every 42 milliseconds (or 24 fps)
        t = t - 42;
        mePlayer.Position = TimeSpan.FromMilliseconds(t);
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        mePlayer.Play();
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // Pause and go to 4th minute of the video then start playing backward
        mePlayer.Pause();                               
        mePlayer.Position = TimeSpan.FromMinutes(4);
        dispatcherTimer.Start();
    }

关于c# - 如何在 WPF 中向后播放视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30955604/

相关文章:

c# - 更改动态创建的控件的属性

c# - C# 中实例成员的 protected 访问?

c# - 如何将 dropshadoweffect 添加到文本框的文本(以编程方式)

wpf - 关于WPF MVVM和用户控件的菜鸟问题

wpf - 在 ComboBox 的 ItemsPanel 上方添加其他控件

c# - Visual Studio 2013 不会在出现错误的代码行上停止

c# - MySQL 与 MonoTouch

c# - 如何从我的日历中删除所有面板?

c# - 异步方法可以在第一个 'await' 之前有昂贵的代码吗?

c# - 为什么我们需要反射?