Wednesday, September 12, 2012

Using the Silverlight Media Player Javascript to Show Video Files in SharePoint 2010

Every now and then a client will have needs for a video player in SharePoint that is just outside what is possible with the out of the box Silverlight video player or Windows Media player.  Luckily SharePoint ships with an extremely handy file titled MediaPlayer.js.  This file is located in the Layouts folder and allows you to render a Silverlight video player on the fly via Javascript.  How cool is that?!

A complete solution of this code can be downloaded at the TechNet Gallery here.

In this post, we'll walk through creating a Document Library to hold our video files, then build a custom Webpart to show the videos.

First, lets create the Document Library.  This is very straight forward, just go to "Site Actions" and click "New Document Library".


Now give it the name "Videos" and choose "None" as the Document Template.


If you're like me your on a Windows 7 machine, and luckily that OS comes with a single video file located under "Libraries\Videos\Sample Videos" called Wildlife.  Its a WMV, and we'll upload that into our new Video library.


After uploading it, we have a single file in our new library, hooray!


Before moving on, you may want to set Permissions on this library basically giving all authenticated users Read access.

Now on to the code!

We'll launch Visual Studio and create a new Visual Webpart project and call it "Silverlight_Video_Player_Webpart_Demo".  Awesome name!


First, we'll open the "VisualWebpart1UserControl.ascx.cs" code behind and add a property to hold a reference to the Webpart code.

 public  VisualWebPart1  WebPart { get ; set ; }
 

Next, we'll open the "VisualWebpart1.cs" file and add in some custom properties and set the "Webpart" property we just created.  We'll need two properties:
  1. The URL to the video file.
  2. The title we want to show in the player.

 [ToolboxItemAttribute (false )]
     public  class  VisualWebPart1  : WebPart 
     {
         #region  Properties
 
         [WebBrowsable (true ),
         Category ("Video" ),
         Personalizable (true ),
         WebDisplayName ("Video Title" ),
         WebDescription ("Video title." )]
         public  string  VideoTitle { get ; set ; }
 

         [WebBrowsable (true ),
         Category ("Video" ),
         Personalizable (true ),
         WebDisplayName ("*Video Url" ),
         WebDescription ("URL to the video to play." )]
         public  string  VideoUrl { get ; set ; }
 
         #endregion 

 
         // Visual Studio might automatically update this path when you change the Visual Web Part project item. 
         private  const  string  _ascxPath = @"~/_CONTROLTEMPLATES/Silverlight_Video_Player_Webpart_Demo/VisualWebPart1/VisualWebPart1UserControl.ascx" ;
 
         protected  override  void  CreateChildControls()
         {
             Control  control = Page.LoadControl(_ascxPath);
             if  (control!= null )  
             {
                 ((VisualWebPart1UserControl )control).WebPart = this ;  
             } 
             Controls.Add(control);
         }
     }
 

So we create the two properties, then in the "CreateChildControls()" method we set the property we created in the User Control.  This will give us access to the custom properties in the User Control.

Now, let's go back to the "VisualWebpart1UserControl.ascx.cs" and add one more property called "UniqueDivId".  We'll use this to generate a unique id for the DIV holding our video player.  This will allow multiple players on the same page and not throw any Javascript errors.

         public  VisualWebPart1  WebPart { get ; set ; }
         public  string  UniqueDivId { get ; set ; }
 

We'll come back the code behind in a moment, let's work on the UI now.  In "VisualWebpart1UserControl.ascx" we'll add a reference to the Javascript file which makes all this possible, the "mediaplayer.js" file.

 <script  type="text/javascript"  src="/_layouts/mediaplayer.js"></script>
 

Below that we'll add two Panel controls to hold all the UI elements.

 <asp:Panel  ID="pnlVideo"  runat="server"  Visible="false"> 
     <div  id="<%= this.UniqueDivId %>"> 
         <script  type="text/javascript"> 
             var  MediaURL = "<%= this.WebPart.VideoUrl %>";
             var  MediaTitle = "<%= this.WebPart.VideoTitle %>";
             var  AutoPlay = false;
             var  Loop = false;
             mediaPlayer.createMediaPlayer(
                 document.getElementById(<%= this.UniqueDivId %>'),
                  <%= this.UniqueDivId %>' ,
                  '235px', '151px',
                 {
                     displayMode:  'Inline',
                     mediaTitle: MediaTitle,
                     mediaSource: MediaURL,
                     autoPlay: AutoPlay,
                     loop: Loop,
                     //previewImageSource: "You can provide an image here to show rather than a black screen before the video plays", 
                     mediaFileExtensions: 'wmv;wma;avi;mpg;mp3;', 
                     silverlightMediaExtensions: 'wmv;wma;mp3;'  
                 });
         </script> 
     </div> 
 </asp:Panel> 
 
 <asp:Panel  ID="pnlError"  runat="server"  Visible="false"> 
     <asp:Label  ID="lblError"  runat="server"  ForeColor="Red"  /> 
 </asp:Panel>
 

In the first Panel called "pnlVideo" we have the Javascript that will render the video.  Here is a breakdown on this code:
  • We set the DIV id to the property from our code behind, thus giving us a unique DIV id.
  • We set some variables for use in our script, most importantly the video URL and title which are coming again from properties in our code behind.
  • We call the mediaPlayer.createMediaPlayer function which is housed in the mediaplayer.js file we referenced earlier.  We pass in the DIV id which is the same as the container DIV id.  Basically we are saying "load the player into this DIV and show it".
  • We set a few more properties needed for the player including the height and width.
In the second Panel called "pnlError" we simply have a Label control that will display any errors.

We have Visible=false set on both Panels so we can control from the code behind which to show.  I like using Panels here for two reasons:
  1. They are standard ASP.NET controls and very predictable.  They render DIVs and are easy and familiar to all developers.
  2. With a single property, Visible, you can control whether their HTML contents are rendered.  Powerful stuff.
Now that we have the UI in place, let's move back to the "VisualWebpart1UserControl.ascx.cs" code behind and wrap it up.

 protected  void  Page_Load(object  sender, EventArgs  e)
         {
             // Get the video URL from the webpart property 
             string  videoUrl = this .WebPart.VideoUrl;
 
             // If the URL is not empty show the player, otherwise show an error 
             if  (!String .IsNullOrEmpty(videoUrl))
             {
                 // Craft a unique ID for each video div 
                 this .UniqueDivId = "div"  + DateTime .Now.Second + DateTime .Now.Millisecond;
 
                 // Show Video 
                 pnlVideo.Visible = true ;
             }
             else 
             {
                 // Show Error 
                 pnlError.Visible = true ;
                 lblError.Text = "Please provide a valid video URL" ;
             }
         }
 

Pretty simple eh?  Here is what this code is doing:
  • First we put the VideoUrl property into a new string variable and then check if its empty or null.
  • If its empty we fall into the Else statement, and we show the error Panel and populate the error label.
  • If we have a valid URL (or at least some kind of string) we move into showing the video.
  • We craft a unique ID for the DIV that holds the video.  This is simply done using the second and millisecond of the current time. 
  • Finally we show the video Panel.
  • The other custom properties are pulled on the UI.
Some things to note here:
  1. This is a demo, if you want to use this in production a couple of things should be changed:
    1. A robust check of the URL being passed in.  We simply check to see if its not an empty string.  If they pass in something bad, it won't kill your page, but you will get an error on the video player.
    2. A robust unique ID generation for the DIV.  A GUID would be good.
OK, now that we have that, we can go place this webpart on our page.  I didn't include it here, but I updated the feature and webpart settings with a nice name and description.

Deploy or debug your solution, place your page into Edit mode, and insert your webpart.


Right off the bat you'll see our code behind code in action.  You'll be presented with an error message asking for a valid URL, nice!


With the page still in Edit mode, use the webpart pull down menu and choose "Edit Web Part".

Now in the Properties pane, you'll see our custom properties under the "Video" header.


Going back to our "Videos" Document Library we can grab the URL for the video we just uploaded.  Just right click on the file and choose "Copy Link Location" or whatever the browser you're using says, Copy URL, etc.


With that copied, just paste it into your properties and give it a good name.


Now click "OK" in the properties panel, and then click "Save and Close" on the page.  When the page refreshes you should see your video with your custom title.


Click the Play icon and watch the ponies run!


And that's it.  Load some new videos into your library and change the URL out.  You can use the contextual menu provided on the player to stop, start, go full screeen, etc.

Some things you can expand on with this code:
  • Allow the user to provide a link to the Document Library, then use some code to query the list and pull the most recent video loaded.
  • Include a link below the video to the Document Library.
  • All kinds of stuff.
Since you have a full code behind, you can do all kinds of cool dev tricks to get and display your vidoes.

A complete solution of this code can be downloaded at the TechNet Gallery here.

Enjoy!







No comments:

Post a Comment