Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C#

Cool Media Player with Silverlight

Rate me:
Please Sign up or sign in to vote.
2.36/5 (10 votes)
7 Sep 2008CPOL 50.1K   1.4K   17   9
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#

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
    }
C#
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)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
VickyC#10-Nov-10 18:01
VickyC#10-Nov-10 18:01 
GeneralHihihi chào anh Minh! Pin
Luyen Ha25-Jul-10 3:25
Luyen Ha25-Jul-10 3:25 
GeneralBecause it gives this error when running your project in VisualStudio 2008 Pin
LuizItatiba20-Aug-09 16:43
LuizItatiba20-Aug-09 16:43 
GeneralMy vote of 1 Pin
smton9-Jul-09 15:46
smton9-Jul-09 15:46 
GeneralSilverlight UI Changes Pin
jherington1-Oct-08 20:59
jherington1-Oct-08 20:59 
GeneralRe: Silverlight UI Changes Pin
Hoàng Lê Minh2-Oct-08 1:07
Hoàng Lê Minh2-Oct-08 1:07 
GeneralRe: Silverlight UI Changes Pin
jherington2-Oct-08 6:17
jherington2-Oct-08 6:17 
Im not 100% certain why your project was not updating the SL UI but on my project, I had a similar problem and solved it by changing the way I handled the RootVisual object on the App.xaml

This is how it should look:

App.xaml:
Page p = new Page();
HtmlPage.RegisterScriptableObject("page", p);
this.RootVisual = p;

Page.xaml:
[ScriptableMember]public void testRoutine(int Id){ do somthing; }

Page.aspx:
plugin.Content.page.testRoutine(1)

Thanks!
GeneralThe solution does not work fine :-o Pin
MeNot29-Sep-08 0:08
MeNot29-Sep-08 0:08 
GeneralRe: The solution does not work fine :-o Pin
Hoàng Lê Minh29-Sep-08 1:02
Hoàng Lê Minh29-Sep-08 1:02 

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

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