Click here to Skip to main content
Licence CPOL
First Posted 7 Sep 2008
Views 25,851
Downloads 583
Bookmarked 15 times

Cool Media Player with Silverlight

By | 7 Sep 2008 | Article
Demo Media player
MediaPlayer

Introduction

This article discusses about using MediaElement to play a multimedia file in Silverlight. It has a simple button, example: play, pause, replay, slide time, fullscreen, mute, unmute and slide volume.

Using the Code

C#

namespace MediaPlayer
{
    [ScriptableType]
    public partial class Page : UserControl
    {
        private DispatcherTimer timer;
        private bool isSliderTimeLock{ get; set;}
        private double currentMediaVolume;
        private double old_Height;
        private double old_Width;
        private double old_MediaHeight;
        private double old_MediaWidth;
        private System.Windows.Interop.SilverlightHost host;

        public Page(string source, bool autoPlay)
        {
            InitializeComponent();

            #region Kiem tra file input la video hay audio de goi 
		giao dien player phu hop
            string[] strings = source.Split('.');
            int count = strings.Length - 1;
            if ((strings[count].StartsWith("wma")) || (strings[count].StartsWith("mp3")))
            {
                VisualStateManager.GoToState(this, "Audio", true);
            }
            else
            {
                VisualStateManager.GoToState(this, "Video", true);
            }
            mePlayer.Source = new Uri(source, UriKind.Relative);
            mePlayer.AutoPlay = autoPlay;
            #endregion

            Loaded += new RoutedEventHandler(Page_Loaded);            
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            isSliderTimeLock = false;
            sliderVolume.Value = 1;
            btnReplay.Opacity = 0.3;
            old_Width = this.Width;
            old_Height = this.Height;
            old_MediaWidth = mePlayer.Width;
            old_MediaHeight = mePlayer.Height;
            host = Application.Current.Host;
            host.Content.IsFullScreen = true;

            HtmlPage.RegisterScriptableObject("mediaPlayer", this);           

            btnPlay.Checked += new RoutedEventHandler(btnPlay_Checked);
            btnPlay.Unchecked += new RoutedEventHandler(btnPlay_Unchecked);
            
            mePlayer.CurrentStateChanged += new RoutedEventHandler
					(mePlayer_CurrentStateChanged);

            //Event MouseLeftButtonDonw and MouseLefButtonUp of 
            //Slider is no longer available in beta 2 --> that's messed
            //sliderTime.MouseLeftButtonDown += new MouseButtonEventHandler
            //(sliderTime_MouseLeftButtonDown);
            //sliderTime.MouseLeftButtonUp += new MouseButtonEventHandler
            //(sliderTime_MouseLeftButtonUp);
            sliderTime.ThumbDragStarted += new EventHandler<EventArgs>
					(sliderTime_ThumbDragStarted);
            sliderTime.ThumbDragCompleted += new EventHandler<EventArgs>
					(sliderTime_ThumbDragCompleted);

            sliderVolume.ValueChanged += new RoutedPropertyChangedEventHandler
					<double>(sliderVolume_ValueChanged);

            btnReplay.Click += new RoutedEventHandler(btnReplay_Click);

            btnMute.Checked += new RoutedEventHandler(btnMute_Checked);
            btnMute.Unchecked += new RoutedEventHandler(btnMute_Unchecked);

            btnFull.Click += new RoutedEventHandler(btnFull_Click);


            btnFullScreen.Click += new RoutedEventHandler(btnFullScreen_Click);
            host.Content.FullScreenChanged += new EventHandler(Content_FullScreenChanged);

            mePlayer.MediaEnded += new RoutedEventHandler(mePlayer_MediaEnded);

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(50);
            timer.Tick += new EventHandler(timer_Tick);          
        }

        void Content_FullScreenChanged(object sender, EventArgs e)
        {
            if (host.Content.IsFullScreen)
            {
                userControl.Width = Application.Current.Host.Content.ActualWidth;
                userControl.Height = Application.Current.Host.Content.ActualHeight;

                mePlayer.Width = Application.Current.Host.Content.ActualWidth;
                mePlayer.Height = Application.Current.Host.Content.ActualHeight;
            }
            else
            {
                userControl.Width = old_Width;
                userControl.Height = old_Height;

                mePlayer.Width = old_MediaWidth;
                mePlayer.Height = old_MediaHeight;
            }
        }

        void btnFullScreen_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = 
			!Application.Current.Host.Content.IsFullScreen;
        }

        void btnFull_Click(object sender, RoutedEventArgs e)
        {
            if(btnFull.Content.Equals("Audio"))
            {
                VisualStateManager.GoToState(this, "Audio", true);
                btnFull.Content = "Video";
            }
            else
            {
                VisualStateManager.GoToState(this, "Video", true);
                btnFull.Content = "Audio";
            }
        }

        void btnMute_Unchecked(object sender, RoutedEventArgs e)
        {
            mePlayer.Volume = currentMediaVolume;
            btnMute.Content = "Mute";
        }

        void btnMute_Checked(object sender, RoutedEventArgs e)
        {
            btnMute.Content = "Unmute";
            currentMediaVolume = mePlayer.Volume;
            mePlayer.Volume = 0;
        }

        void btnReplay_Click(object sender, RoutedEventArgs e)
        {
            if (btnReplay.Opacity.Equals(1))
            {
                mePlayer.Position = TimeSpan.FromMilliseconds(0);
                mePlayer.Play();
            }
        }

        void sliderVolume_ValueChanged(object sender, 
		RoutedPropertyChangedEventArgs<double> e)
        {
            mePlayer.Volume = sliderVolume.Value;
        }

        

        void sliderTime_ThumbDragCompleted(object sender, EventArgs e)
        {
            //tbTime.Text = "mouse up" + isSliderTimeLock.ToString();
            isSliderTimeLock = false;
            mePlayer.Position = TimeSpan.FromMilliseconds
	     (mePlayer.NaturalDuration.TimeSpan.TotalMilliseconds * sliderTime.Value);
        }

        void sliderTime_ThumbDragStarted(object sender, EventArgs e)
        {
            isSliderTimeLock = true;
        }

        void mePlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            mePlayer.Position = TimeSpan.FromMilliseconds(0);
            sliderTime.Value = 0;
            btnPlay.IsChecked = false;
            //btnPlay_Unchecked(sender, e);
            btnReplay.Opacity = 1;
        }

        void mePlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            if(mePlayer.CurrentState == MediaElementState.Playing)
            {
                timer.Start();
            }
            else
            {
                timer.Stop();
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if((mePlayer.NaturalDuration.TimeSpan.TotalSeconds > 0) && 
					(isSliderTimeLock == false))
            {
                //tbTime.Text = string.Format("{0:00}:{1:00}", 
                //mePlayer.Position.Minutes, mePlayer.Position.Seconds)+
                //"/"+mePlayer.NaturalDuration.TimeSpan.TotalSeconds.ToString();
                tbTime.Text = string.Format("{0:00}:{1:00}", 
			mePlayer.Position.Minutes, mePlayer.Position.Seconds);
                sliderTime.Value = mePlayer.Position.TotalSeconds/
			mePlayer.NaturalDuration.TimeSpan.TotalSeconds;
            }
        }

        void btnPlay_Unchecked(object sender, RoutedEventArgs e)
        {
            mePlayer.Pause();
            btnPlay.Content = "Play";
        }

        void btnPlay_Checked(object sender, RoutedEventArgs e)
        {
            mePlayer.Play();
            btnPlay.Content = "Pause";
        }
      
        #region Method for interacting with javascript (API)
        [ScriptableMember]
        public double getDoubleValue()
        {
            return (double)43;
        }

        [ScriptableMember]
        public void FullScreen()
        {
            userControl.Width = Application.Current.Host.Content.ActualWidth;
            userControl.Height = Application.Current.Host.Content.ActualHeight;

            mePlayer.Width = Application.Current.Host.Content.ActualWidth;
            mePlayer.Height = Application.Current.Host.Content.ActualHeight;
        }
        [ScriptableMember]
        public void Pause()
        {
            btnPlay.Content = "Play";
            btnPlay.IsChecked = true;
            mePlayer.Pause();
        }
        [ScriptableMember]
        public void Play()
        {
            btnPlay.Content = "Pause";
            btnPlay.IsChecked = false;
            mePlayer.Play();
        }
        [ScriptableMember]
        public void Stop()
        {
            btnPlay.Content = "Play";
            btnPlay.IsChecked = true;
            mePlayer.Stop();
            sliderTime.Value = 0;
        }
        [ScriptableMember]
        public void Volume(double vol)
        {
            mePlayer.Volume = vol;
            sliderVolume.Value = vol;
        }
        [ScriptableMember]
        public void Seek(double pos)
        {
            if ((mePlayer.NaturalDuration.TimeSpan.TotalSeconds > pos) && (pos >= 0))
            {
                mePlayer.Position = TimeSpan.FromSeconds(pos);
                sliderTime.Value = 
                     mePlayer.Position.TotalSeconds / 
			mePlayer.NaturalDuration.TimeSpan.TotalSeconds;
            }
        }
        [ScriptableMember]
        public void LoadSource(string url)
        {
            //Stop();
            mePlayer.Source = new Uri(url, UriKind.Relative);
        } 
        #endregion
    }
public class CustomSlider:System.Windows.Controls.Slider
    {
        public CustomSlider():base()
        {
            DefaultStyleKey = typeof (CustomSlider);
        }
        /// <summary>

        /// Thrown when the thumb has been clicked, and dragging is initiated

        /// </summary>
        public event EventHandler<EventArgs> ThumbDragStarted;

        /// <summary>

        /// Thrown when the thumb has been released

        /// </summary>
        public event EventHandler<EventArgs> ThumbDragCompleted;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            //Set up drag event handlers
            Thumb thumb = this.GetTemplateChild("HorizontalThumb") as Thumb; 
			if (thumb != null)
            {

                thumb.DragStarted += new DragStartedEventHandler(thumb_DragStarted);
                thumb.DragCompleted += new DragCompletedEventHandler(thumb_DragCompleted);
            }
        }

        void thumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            OnThumbDragCompleted(this, new EventArgs());
        }
        void thumb_DragStarted(object sender, DragStartedEventArgs e)
        {
            OnThumbDragStarted(this, new EventArgs());
        }
        public virtual void OnThumbDragStarted(object sender, EventArgs e)
        {
            if (ThumbDragStarted != null)
                ThumbDragStarted(sender, e);
        }
        protected virtual void OnThumbDragCompleted(object sender, EventArgs e)
        {
            if (ThumbDragCompleted != null)

                ThumbDragCompleted(sender, e);
        }
    }
}

Points of Interest

I'm very surprised at Slider in Silverlight beta 2, it have MouseLeftButtonUp and MouseLeftButtonDown events, but these don't work. I have to inherit Slider class and code the above event by hand.

History

  • 7th September, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Hoàng Lê Minh

Software Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberVickyC#18:01 10 Nov '10  
GeneralHihihi chào anh Minh! PinmemberHa Luyen3:25 25 Jul '10  
GeneralBecause it gives this error when running your project in VisualStudio 2008 PinmemberLuizItatiba16:43 20 Aug '09  
GeneralMy vote of 1 Pinmembersmton15:46 9 Jul '09  
GeneralSilverlight UI Changes Pinmemberjherington20:59 1 Oct '08  
GeneralRe: Silverlight UI Changes PinmemberHoàng Lê Minh1:07 2 Oct '08  
I've check my project, it works fine. I will update this project on CodeProject tomorrow
GeneralRe: Silverlight UI Changes Pinmemberjherington6:17 2 Oct '08  
GeneralThe solution does not work fine :-o PinmemberMeNot0:08 29 Sep '08  
GeneralRe: The solution does not work fine :-o PinmemberHoàng Lê Minh1:02 29 Sep '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 7 Sep 2008
Article Copyright 2008 by Hoàng Lê Minh
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid