[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Control a video with the WPF MediaElement in C#

[Control a video with the WPF MediaElement in C#]

This example shows how you can control an MP4 video with WPF's MediaElement control. The control provides a surprisingly nice assortment of features that let you play, pause, position, and otherwise control a video.

The following XAML code defines the MediaElement used by this example.

<MediaElement x:Name="minionPlayer" Margin="5" Grid.Row="0" Grid.Column="0" MediaOpened="minionPlayer_MediaOpened" ScrubbingEnabled="True" LoadedBehavior="Manual" Source="minions.mp4"/>

Most of that code is self-explanatory. The control's name is minionPlayer. When it finishes opening some media, in this case the MP4 video named "minions.mp4."

At design time, I added that video file to the project and set its "Copy to Output Directory" property to "Copy if newer." That way the video is available in the executable directory so the program can load it into the MediaElement.

Probably the least obvious property in this XAML code is the ScrubbingEnabled. That property is set to true to allow the control to update its display if the video is repositioned when the video is not running. (I have no idea why it's called "ScrubbingEnabled.")

The LoadedBehavior property is set to Manual so the video doesn't start playing as soon as the control loads.

When it starts the program executes the following code to prepare to run the video.

// A timer to display the video's location. private DispatcherTimer timerVideoTime; // Create the timer and otherwise get ready. private void Window_Loaded(object sender, RoutedEventArgs e) { timerVideoTime = new DispatcherTimer(); timerVideoTime.Interval = TimeSpan.FromSeconds(0.1); timerVideoTime.Tick += new EventHandler(timer_Tick); minionPlayer.Stop(); }

This code creates a new DispatcherTimer to monitor the video's progress. It finishes by calling the MediaElement control's Stop method. That makes the control load its media so you can see it. If you omit that statement, the control is invisible and the program's scroll bar doesn't show any position.

The following event handler executes when the media file finishes loading.

private void minionPlayer_MediaOpened(object sender, RoutedEventArgs e) { sbarPosition.Minimum = 0; sbarPosition.Maximum = minionPlayer.NaturalDuration.TimeSpan.TotalSeconds; sbarPosition.Visibility = Visibility.Visible; }

This code sets the ScrollBar control's Minimum and Maximum properties so it can represent the video's full duration.

The program uses two helper methods, ShowPosition and EnableButtons. The following code shows the ShowPosition method.

// Show the play position in the ScrollBar and TextBox. private void ShowPosition() { sbarPosition.Value = minionPlayer.Position.TotalSeconds; txtPosition.Text = minionPlayer.Position.TotalSeconds.ToString("0.0"); }

This method displays the value of the MediaElement control's Position property in the program's ScrollBar and TextBox.

The following code shows the EnableButtons method.

// Enable and disable appropriate buttons. private void EnableButtons(bool is_playing) { if (is_playing) { btnPlay.IsEnabled = false; btnPause.IsEnabled = true; btnPlay.Opacity = 0.5; btnPause.Opacity = 1.0; } else { btnPlay.IsEnabled = true; btnPause.IsEnabled = false; btnPlay.Opacity = 1.0; btnPause.Opacity = 0.5; } timerVideoTime.IsEnabled = is_playing; }

This method enables or disables the Play and Pause buttons depending on whether the video is currently playing. For example, if the video is playing then the Play button is disabled and the Pause button is enabled.

The code sets the buttons' Opacity to 1.0 for enabled buttons (so they appear normally) and 0.5 for disabled buttons (so they appear grayed out).

The timer's Tick event handler, shown in the following code, simply calls ShowPosition to update the position display.

private void timer_Tick(object sender, EventArgs e) { ShowPosition(); }

The following code shows how the buttons control the MediaElement control.

private void btnPlay_Click(object sender, RoutedEventArgs e) { minionPlayer.Play(); EnableButtons(true); } private void btnPause_Click(object sender, RoutedEventArgs e) { minionPlayer.Pause(); EnableButtons(false); } private void btnStop_Click(object sender, RoutedEventArgs e) { minionPlayer.Stop(); EnableButtons(false); ShowPosition(); } private void btnRestart_Click(object sender, RoutedEventArgs e) { minionPlayer.Stop(); minionPlayer.Play(); EnableButtons(true); } private void btnFaster_Click(object sender, RoutedEventArgs e) { minionPlayer.SpeedRatio *= 1.5; } private void btnNext_Click(object sender, RoutedEventArgs e) { minionPlayer.Position += TimeSpan.FromSeconds(10); ShowPosition(); } private void btnSlower_Click(object sender, RoutedEventArgs e) { minionPlayer.SpeedRatio /= 1.5; } private void btnPrevious_Click(object sender, RoutedEventArgs e) { minionPlayer.Position -= TimeSpan.FromSeconds(10); ShowPosition(); }

The buttons' code is pretty self-explanatory. The MediaElement control's Play method starts the video, its Pause method pauses it, and its Stop method stops the video and rewinds to the beginning.

When the video isn't playing, you can enter a time in the TextBox and then click the Set Position button. When you do, the following code executes.

private void btnSetPosition_Click(object sender, RoutedEventArgs e) { TimeSpan timespan = TimeSpan.FromSeconds(double.Parse(txtPosition.Text)); minionPlayer.Position = timespan; ShowPosition(); }

This code converts the time you entered into a TimeSpan and sets the player's Position property to it. It then calls ShowPosition to update the position display.

That's all there is to it. The MediaPlayer provides a lot of features for controlling the video.

Note that the MediaPlayer may not be able to provide all of these features for all media. For example, some media sources may not support setting the position directly.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.