How to play video backwards in WPF?

I want to smoothly play videos backwards in WPF. I am using MediaElement

to play video. I am reading this post which suggests changing periodically MediaElement.Position

to mimic the rewind behavior.

I tried the following code to change 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
    }
}

      

In the above code, I am trying to play a video backwards from 2 min to 1 min. This gives me a "System.OverflowException" on mePlayer.Position = TimeSpan.FromSeconds(t)

.

If anyone knows how to play videos in WPF, please help me to achieve this effect. Thank.

+3


source to share


1 answer


To make it smooth, you must use Timer

. Assuming the frame rate is 24 frames per second, this means that it is one frame every 1/24 = 0.0416 seconds, or roughly 42 milliseconds. So if your timer goes out every 42ms, you can move mePlayer.Position

back:

XAML:

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

      



code:

    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();
    }

      

+1


source







All Articles