Tuesday, December 9, 2008

How to Create Generic Media Player Web Part

In this post I would show you how to create a web part that is intelligent enough to load and play a media file with a proper media player. when my client wanted to have a web part that plays windows media I came up with the idea of embedding the media player ActiveX object using HTML <OBJECT> tag. Then it occurred to me that if I can do it for Windows media player, why can not I do it for Flash player, Real player or any media player for that matter.

Enough on background and let's start coding.

For the sake of simplicity, I will use 3 attributes that are common to almost all the players. those are width, height and visibility of the controls of the player. one good thing about this web part is that it is capable of extracting media URL from a URL query parameter as well as from user entered web part property. for this I define another property called 'mediaURL'.

I define 4 web part properties for the above attributes as follows;

        private int height = 300;
        private int width = 400;
        private bool showControls = true;
        private String mediaURL;

then, define 4 web part properties;

        [Description("Media Player Settings"),WebPartStorageAttribute(Storage.Shared),
        Category("Media Player Settings"),Browsable(true),FriendlyName("Height")]
        public int PlayerHeight
        {
            get { return height; }
            set { height = value; }
        }
 
        [Description("Media Player Settings"),WebPartStorageAttribute(Storage.Shared),
        Category("Media Player Settings"),Browsable(true),FriendlyName("Width")]
        public int PlayerWidth
        {
            get { return width; }
            set { width = value; }
        }
 
        [Description("Media Player Settings"),WebPartStorageAttribute(Storage.Shared),
        Category("Media Player Settings"),Browsable(true),FriendlyName("URL")]
        public string MediaURL
        {
            get { return mediaURL; }
            set { mediaURL = value; }
        }
 
        [Description("Media Player Settings"),WebPartStorageAttribute(Storage.Shared),
        Category("Media Player Settings"),Browsable(true),FriendlyName("Show Controls")]
        public bool ShowControls
        {
            get { return showControls; }
            set { showControls = value; }
        }

Now that we have all the web part properties defined, we can go ahead and implement the web part.
The very first thing I am going to do is override CreateChildControls method and add a global Label that renders HTML.

    protected override void CreateChildControls()
    {
        try
        {
            base.CreateChildControls();
            displayLabel = new Label();
            if (Page.Request.QueryString["mediaurl"] == null || 
                Page.Request.QueryString["mediaurl"].ToString().Equals(""))
            {
                displayLabel.Text = "set media url...";
            }
            else
                MediaURL = Page.Request.QueryString["mediaurl"].ToString();
            Controls.Add(this.displayLabel);
        }
        catch (Exception ex)
        {
            HandleException(ex);
        }
    }

In order to render HTML we have to override void Render(HtmlTextWriter writer) in the web part. this is where all the magic happens.

protected override void Render(HtmlTextWriter writer)
    {
        this.EnsureChildControls();
        try
        {
            if (!String.IsNullOrEmpty(MediaURL))
            {
                String ext = MediaURL.Substring(MediaURL.LastIndexOf('.') + 1);
                MediaPlayerFactory factory = MediaPlayerFactory.GetInstance();
                MediaPlayer player = factory.GetMediaPlayer(ext);
                player.Height = PlayerHeight;
                player.Width = PlayerWidth;
                player.MediaURL = MediaURL;
                player.ShowControls = ShowControls;
                writer.Write(player.GetHTML()); 
                this.displayLabel.RenderControl(writer);
            }else
            {
                //Render Error message in the label
                HandleException(new Exception("set media url...."), writer);
            }
        }
        catch (Exception e)
        {
            //handle Error eroperly
            HandleException(e,writer);
        }   
    }


Now, I'll explain the above code line by line.


    String ext = MediaURL.Substring(MediaURL.LastIndexOf('.') + 1);
    MediaPlayerFactory factory = MediaPlayerFactory.GetInstance();
    MediaPlayer player = factory.GetMediaPlayer(ext);

First, the file extension is extracted. then MediaPlayerFactory Singleton Object is instantiated. this factory will expose GetMediaPlayer method that returns a MediaPlayer object based on the file extension.

    player.Height = PlayerHeight;
    player.Width = PlayerWidth;
    player.MediaURL = MediaURL;
    player.ShowControls = ShowControls;

Player properties are set based on the web part properties.

    writer.Write(player.GetHTML());
    this.displayLabel.RenderControl(writer);

Render the HTML in the Label.

Up to this point it is very straight forward and all related to web parts. All other areas of code is pure OOP. I hope you will understand the code.

Please note that I have tested the HTML
<OBJECT> tag for Windows media player and not for the others. if you find any problems with other media players I am more than happy to assist.

Find the full code for this article at http://sites.google.com/site/bhakthil/Home/MediaWebPart.zip