Tuesday, November 23, 2010

WPF - Media Player in WPF

In this article i will show you how to use Media Element in WPF and i will explore some of the functionalities such as drag and drop media file in the media element, Play, Pause, Stop, Back and Forward,Change the volume of the media and fullscreen mode. 

We can see above functionalities step by step.

Step 1
Create a WPF application.

Step 2
Now we will first design the application so that all the functionalities would be clear to us.

Add a Media Element, two slider bar,
and several Template buttons for the functions to be achieved.it is look like this

























Click on image for better view

Download Source Code and view the XAML code, style and Template XAML code in the ResourceDictionary

Step 3
In the constructor of the Application add a DispatcherTimer object and disabled a several Controls,it is look like this



 #region Declaration

        private DispatcherTimer Timer = null;
        private Double CurrentPosition = 0;
        private Boolean IsSeekBarDragging = false;
        private Boolean IsFullscreen = false; 

        #endregion

 public MainWindow()
        {
            this.InitializeComponent();

            #region Timer Section

            try
            {
                Timer = new DispatcherTimer();
                Timer.Interval = TimeSpan.FromMilliseconds(200);
                Timer.Tick += new EventHandler(Timer_Tick);
            }
            catch (Exception)
            { 
            }
            #endregion

            EnabledDisabledControls(false); // disabled controls

            btnPlay.IsEnabled = false; // disabled play button control  
        }

 /// <summary>
        /// Enable and Disabled Controls
        /// </summary>
        /// <param name="Flag">for enable set true and for disable set false</param>
        private void EnabledDisabledControls(Boolean Flag)
        {
            try
            {
                btnPause.IsEnabled = Flag;
                btnStop.IsEnabled = Flag;
                btnForward.IsEnabled = Flag;
                btnBackword.IsEnabled = Flag;
                SeekBar.IsEnabled = Flag;
                VolumeBar.IsEnabled = Flag;
                btnFullScreen.IsEnabled = Flag;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

Step 4
Drag and Drop the .wmv file in media element,it is look like this

First Set AllowDrop property as True in the Window element and then add the below code on Window_Drop event.

 /// <summary>
        /// Drop the .wmv file in the media element
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Drop(object sender, DragEventArgs e)
        {
            try
            {

                String[] FileName = (String[])e.Data.GetData(DataFormats.FileDrop, true);

                if (FileName.Length > 0)
                {
                    String VideoPath = FileName[0].ToString();

                    if (CheckWMAExtension(VideoPath))
                    {
                        MediaPlayer.Source = new Uri(VideoPath);
                        DDMessage.Text = "     Click Play button";

                        btnPlay.IsEnabled = true;
                    }
                    else
                    {
                        MessageBox.Show("you are choose wrong file");  
                    }
                }

                e.Handled = true;  
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Check .wmv file extension

 /// <summary>
        ///  Check .wma File Extension
        /// </summary>
        /// <param name="FilePath">Specify the file path</param>
        /// <returns>Boolean</returns>
        private Boolean CheckWMAExtension(String FilePath)
        {
            Boolean Flag = false; 
            try
            {
                String Extension=System.IO.Path.GetExtension(FilePath);

                if (Extension != String.Empty)
                {
                    if (Extension == ".wmv")
                    {
                        Flag = true; 
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return Flag; 
        }

Step 5
Add the below code in Timer_Tick event,it is look like this


 /// <summary>
        ///  Timer Tick Event    
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!IsSeekBarDragging)
                {
                    SeekBar.Value = MediaPlayer.Position.TotalSeconds;
                    CurrentPosition = SeekBar.Value;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

Step 6
In the MediaElement's MediaOpened event add the following code,it is look like this

 /// <summary>
        /// After media opened start the timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            try
            {
               
                if (MediaPlayer.NaturalDuration.HasTimeSpan)
                {
                    TimeSpan ts = MediaPlayer.NaturalDuration.TimeSpan;
                    SeekBar.Maximum = ts.TotalSeconds;
                }

                Timer.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 7
Play function.
Add the below code in Play Button Click event,it is look like this
  
  /// <summary>
        /// Play the media
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DDMessage.Visibility = System.Windows.Visibility.Collapsed;

                MediaPlayer.Play();

                EnabledDisabledControls(true);

                btnPlay.IsEnabled = false;   
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 8
Pause function.
Add the below code in Pause Button Click event,it is look like this

 /// <summary>
        /// Pause the media
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MediaPlayer.Pause();

                btnPause.IsEnabled = false;

                btnPlay.IsEnabled = true;   
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 9
Stop function.
Add the below code in Stop Button Click event,it is look like this

/// <summary>
        /// Stop the media
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MediaPlayer.Stop();

                EnabledDisabledControls(false);

                btnPlay.IsEnabled = true;   
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 10
Move Back function.
Add the below code in Move Back Button Click event,it is look like this

 /// <summary>
        /// Move back
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBackword_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MediaPlayer.Position -= TimeSpan.FromSeconds(5);     
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 11
Move Forward function.
Add the below code in Move Forward Button Click event,it is look like this

 /// <summary>
        /// move forward
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForward_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MediaPlayer.Position += TimeSpan.FromSeconds(5);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Step 12
Seek Bar

Now Add two events to the slider control, events are Thumb.DragStarted and Thumb.DragCompleted in XAML behind.it is look like this

<Slider x:Name="SeekBar" Height="24" Margin="240,0,24,103" VerticalAlignment="Bottom" Style="{DynamicResource SimpleSlider}" FocusVisualStyle="{DynamicResource RadioButtonFocusVisual}" Thumb.DragStarted="SeekBar_DragStarted" Thumb.DragCompleted="SeekBar_DragCompleted" >
                <Slider.Background>
                    <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
                        <GradientStop Color="#FF09F5BA" Offset="1"/>
                        <GradientStop Color="#FF07664E"/>
                    </LinearGradientBrush>
                </Slider.Background>
            </Slider>

In the above event handlers add the following code,it is look like this

 #region Drag the Seek Bar
        private void SeekBar_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
        {
            try
            {
                IsSeekBarDragging = true;  
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

        private void SeekBar_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            try
            {
                IsSeekBarDragging = false;
                MediaPlayer.Position = TimeSpan.FromSeconds(SeekBar.Value);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }
        #endregion

Step 13
Change the volume of the media,it is look like this

Add the below code in Slider ValueChanged event,it is look like this

   /// <summary>
        ///Change the volume of the media
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                try
                {
                    MediaPlayer.Volume = (double)VolumeBar.Value;
                }
                catch (Exception)
                { }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 14
FullScreen Mode

Add the below code in Full screen button event,it is used for run the media element in fullscreen mode,it is look like this

  /// <summary>
        /// Switch full screen mode
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFullScreen_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                IsFullscreen = true;  

                LayoutRoot.Children.Remove(MediaPlayer);
               
                this.Background = new SolidColorBrush(Colors.Black);
              
                this.Content = MediaPlayer;
                MediaPlayer.Margin = new Thickness(24, 59, 24, 62);
                
                this.WindowState = WindowState.Maximized;
              


                MediaPlayer.Position = TimeSpan.FromSeconds(CurrentPosition);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Add the below code in window keydown event,it is used for exit fullscreen mode,it is look like this

 /// <summary>
        ///  Exit from full screen mode after press Esc button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (IsFullscreen == true)
                {
                    if (e.Key == Key.Escape)
                    {
                        this.Content = LayoutRoot;
                        LayoutRoot.Children.Add(MediaPlayer);
                        MediaPlayer.Margin = new Thickness(24, 59, 24, 189);
                        this.WindowState = WindowState.Normal;

                        MediaPlayer.Position = TimeSpan.FromSeconds(CurrentPosition);

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 15
Add the below code in MediaEnded event,it is look like this

 /// <summary>
        /// after media ended stop the media player and disabled the controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            try
            {
                MediaPlayer.Stop();

                MediaPlayer.Source = null;

                EnabledDisabledControls(false);

                btnPlay.IsEnabled = false;

                DDMessage.Visibility = System.Windows.Visibility.Visible;
                DDMessage.Text = "Drag and Drop .WMV file";  
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 16
Close the Application.

Add the below code in Close button event,it is look like this


/// <summary>
        /// Close the application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Application.Current.Shutdown();    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Run the Project.

Download
Download Source Code

5 comments:

  1. Thank you for this lesson...

    ReplyDelete
  2. download source code is not working..

    ReplyDelete
  3. Download source code is not working

    ReplyDelete
  4. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me. I am a regular follower of your blog.
    Really very informative post you shared here. Kindly keep blogging.
    Java training in Btm layout
    Java training in Rajaji nagar
    Java training in Kalyan nagar
    Java training in Kalyan nagar
    Java training in Jaya nagar


    ReplyDelete