Tuesday, December 2, 2008

Silverlight 2 : Playing Multiple Videos with One Media Element

You may think that Playlist is always good option, though it is, sometimes it takes too much time to develop and test, so for small amount of video files, you can do play multiple videos by making use of Media_Ended() event.

I found many new things while doing demo of this, First surprise was that I was not able to declare “var” globally, I am researching on it why it had happened, Hashtable and ArrayList are seems to be not allowed in Silverlight though they are normal collections with .net framework, a surprise for me !

Code goes here :

public partial class Media : UserControl
    {


        int i = 1,j;
        Dictionary<int, string> temp = null;


        public Media()
        {
            InitializeComponent();

            temp = new Dictionary<int, string>();

            temp.Add(1, "http://localhost/Video1.wmv");
            temp.Add(2, "http://localhost/Video2.wmv");
            temp.Add(3, “http://localhost/Video3.wmv”);

            j = temp.Count;

            this.Loaded += new RoutedEventHandler(Media_Loaded);
            MasterMedia.MediaEnded += new RoutedEventHandler(MasterMedia_MediaEnded);
        }


        void MasterMedia_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (i == j)
            {
                MasterMedia.Stop();
            }
            else
            {
                i++;
                MasterMedia.Source = new Uri(temp[i], UriKind.Absolute);            
            }
        }


        void Media_Loaded(object sender, RoutedEventArgs e)
        {
            if(i == 1)
              MasterMedia.Source = new Uri(temp[i], UriKind.Absolute);            
        }
}

As I told you that Hashtable and Arraylist was not in position so I have declare a “Dictionary” over here globally. I am adding URLs of media in it along with a key as integer so as to recognize what needs to be play. That can be track using global variables i and j.

This is the simplest way to play media in loop and you will observe the great usage of Media_Ended() event over here, how every time its getting fired. Do let me know your feedback on this if there are any more smart ways to do so.

Vikram.

No comments: