Creating a Customizable Media Player in Silverlight 4

Introduction

Silverlight, a Microsoft product, is the application framework that provides rich interaction in thin (Web) environment. It is often weighed against Adobe's Flash. Silverlight has come a long way from the version 1.0 to the Silverlight 4.0. Refer to the section titled "References" at the end of the article that provides you the necessary links to understand the improvements in features of each version.

The User interface layout of the Silverlight application is created using XAML - markup.

The Wiki link of Microsoft clearly states the flow of a Silverlight application:

"A Silverlight application starts by invoking the Silverlight control from the Hyper Text Markup Language (HTML) page, which then loads up a XAML file. The XAML file contains a Canvas object, which acts as placeholder for other elements."

Let's see how we can develop our own customizable media player using Silverlight.

First, create a Silverlight Application. You would choose to create a Silverlight Application from the File - New Project menu. The following window would appear.


Figure 1


Figure 1

Give a name for the project, and click on OK. It would create two projects for you.

Note the sample aspx and HTML pages that are added by default. Similarly in the Silverlight Library project, the App and MainPage XAML files are added by default too.

We will modify the first project--Silverlight Library to contain the Media Player Control. The Media Player control would comprise two user controls.

The second project - the Web application would be used to pass parameters to the Silverlight application and is used to host the Silverlight Media Player Control.

The diagram below shows the composition of the Media Player control. (The final user control is called CustomizedMediaPlayer).

The Media Element is part of the default Silverlight controls. Note that there is also a Media Control available in the Silverlight Toolkit. At the end of the article, there is a link that talks about the Silverlight Toolkit.

The same link also provides you the link to download the Toolkit. It is a simple installation and ease to use.

Back to our application, modify the App.XAML.cs to hook the Startup, Exit and Unhandled Exception events. The sample code is as shown below:

<CODE>
public App()
{
//hook events
      this.Startup            += this.Application_Startup;
      this.Exit               += this.Application_Exit;
      this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
</CODE>

Modify the Application_Startup method code like below:

<CODE>
private void Application_Startup(object sender, StartupEventArgs e)
{
   //Set Page as the Root Visual.
   this.RootVisual = new Page();


  Dictionary<string, string> inputs = new                            
  Dictionary<string, string>();

  if (e.InitParams != null)
  {
     	   //Add the data in the initParams
    	   //to the Resource.
         foreach (var data in e.InitParams)
         {
             inputs.Add(data.Key, data.Value);
         }
  inputs.Add("Skin", "SimpleResources");
         
   this.Resources.Add("InputParams",                                                                
inputs);
    }
}
</CODE>

InitParameters: To pass information from an ASPX page to a Silverlight library, you would make use of the Property called InitParameters. They are of key-value type of collection and are comparable to vars in Flash. Yes, it would be set up in the markup of the HTML page.

One has to just pass a comma separated Key-Value pairs like shown below:

"param1=value1,param2=value2,param3=value3" 

After the parameters are defined and set values, you would use the Application_Startup event handler to capture the init params. Look above for example.

The Control and the Skin parameter allow you to set the skins for the control.


Figure 3

The attached solution with this article consists of two Media player controls in the Silverlight library.

The Customized Media Player control in the Silverlight Library is the Media Control. It's comprised of ucMediaElement and ucMediaElementControl.

The ucMediaControl contains the Media Element and the ucMediaElementControl contains the controls required to navigate in the Media Control.

Let's first create the ucMediaControl: The markup would look like below:

<CODE>
<UserControl x:Class="SilverLightLibrary.ucMediaElement"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows" >	         <Grid x:Name="LayoutRoot" Background="White" >
            <Grid.RowDefinitions>
                <RowDefinition x:Name="VideoRow" Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition x:Name="VideoColumn" />
            </Grid.ColumnDefinitions>
<Border CornerRadius="1" BorderThickness="2" Margin="2" BorderBrush="{StaticResource MyBorderBrush}">
            <MediaElement Name="mediaPlayer" Grid.Row="0"></MediaElement>
        </Border>
    </Grid>
</UserControl>
</CODE>

The ucMediaControl element contains a Grid. The grid has a Row and a Column. The MediaElement is present in the Row. Note the use of the Borderbrush property for the border element. It is loaded from Resources.



Creating a Customizable Media Player in Silverlight 4

The ucMediaControl contains the controls needed to navigate in the Media Player. It consists of the below components:

  • Play-Pause button
  • Video Position Slider
  • Full screen button
  • Mute button
  • Next button

Here is the markup:

<CODE>
<UserControl x:Class="SilverLightLibrary.ucMediaElementControls"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="500" >
    <Grid x:Name="LayoutRoot" Background="Black" VerticalAlignment="Top">
      
<!-- Border for the media control -->
<Border CornerRadius="1" BorderThickness="2" Margin="2" BorderBrush="{StaticResource MyBorderBrush}">
                
<!-Stack Panel for the buttons. Set the orientation to Horizontal-->
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Height="20" Background="#FF000000">
      <Button x:Name="Prev" Content="Prev" Click="PrevButton_Click" />             

<!-The Play- pause button -->
<ToggleButton x:Name="btnPlayPause" Template="{StaticResource PlayButtonTemplate}" Content="ll" Click="Button_Click"
      IsChecked="True" Margin="2,0,0,0"/>

      <!-Slider for Video Poistion -->
<Slider  MouseLeftButtonDown="sliderPosition_MouseLeftButtonDown" Margin="2,0,0,0" x:Name="sliderPosition"   ValueChanged="sliderPosition_ValueChanged"
      Width="240" Minimum="0" Maximum="1" 
MouseLeftButtonUp="sliderPosition_MouseLeftButtonUp" >
      </Slider>

      <!-Text block to show the duration  of the video.-->
<TextBlock x:Name="txtDuration"  Height="12" Margin="2,0,0,0"
      FontFamily="Verdana" FontSize="10" Text="00:00" TextWrapping="Wrap" 
      FontStyle="Normal" HorizontalAlignment="Right"
      TextAlignment="Right" />

      <!-Button to toggle Full Screen -->
<Button x:Name="btnFullScreen" ToolTipService.ToolTip="FullScreen" Margin="2,0,0,0" Click="btnFullScreen_Click"
Template="{StaticResource ButtonTemplate}" VerticalAlignment="Center">
<Path Height="14.375" HorizontalAlignment="Stretch" 
VerticalAlignment="Bottom" RenderTransformOrigin="0.212389379739761,0.208695650100708" 
Data="M10.181361,8.375 L12.844413,11.008244 L14.125,9.7418737 L14.125,14.375 L9.675765,14.374833 L10.906104,13.158273 L8.125,10.408315 L10.181361,8.375 z M3.9666855,8.375 L6,10.431361 L3.3667567,13.094413 L4.6331258,14.375 L0,14.375 L0.00016707927,9.925765 L1.2167276,11.156104 L3.9666855,8.375 z M9.4918737,0 L14.125,0 L14.124833,4.449235 L12.908273,3.2188957 L10.158315,6 L8.125,3.943639 L10.758244,1.2805867 L9.4918737,0 z M0,0 L4.449235,0.00016686507 L3.2188957,1.2167276 L6,3.9666855 L3.943639,6 L1.280587,3.3667567 L0,4.6331258 L0,0 z"
Fill="#FF7F7F7F" Stretch="Fill" Stroke="#FF000000" StrokeThickness="0" />
</Button>

	<!-Text Block for Volume. -->
<TextBlock x:Name="txtVol" Text="Vol:" VerticalAlignment="Center" Margin="2,0,0,0"></TextBlock>
      <Slider x:Name="sliderVolume" Margin="2,0,0,0"  
      Style="{StaticResource SliderStyle}" Width="50"      
VerticalAlignment="Center" ValueChanged="sliderVolume_ValueChanged" Minimum="0" Maximum="1"  ></Slider>

      <!-The Mute button -->
      <ToggleButton IsChecked="false"  x:Name="btnMute" 
Template="{StaticResource MuteButtonTemplate}" Click="btnMute_Click" VerticalAlignment="Center" Margin="2,0,0,0" Content="On"/>

      <!-The Next button -->
      <Button x:Name="Next" Content="Next" Click="NextButton_Click" >
      </Button>

</StackPanel>
</Border>
    </Grid>
</UserControl>
</CODE>

Now, let's create the Media Player user control that would consist these two user controls.

<CODE>
<UserControl x:Class="SilverLightLibrary.CustomizedMediaPlayer" x:Name="ucSkin1Player"
    	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    	xmlns:ns="clr-namespace:SilverLightLibrary" Height="700"
   	>
        <Grid x:Name="LayoutMedia" Background="White" >
            <Grid.RowDefinitions>
                <RowDefinition  Height="Auto"></RowDefinition>
                <RowDefinition  Height="Auto" ></RowDefinition>
            </Grid.RowDefinitions>
<ns:ucMediaElement x:Name="ucMediaPlayer" Grid.Row="0"></ns:ucMediaElement>
<ns:ucMediaElementControls x:Name="ucMediaPlayerControls" Grid.Row="1" VerticalContentAlignment="Top" VerticalAlignment="Top"></ns:ucMediaElementControls>
        </Grid>
    </UserControl>
</CODE>

The media player and the controls are added to the New User Control. Go to code-behind and set the mediaplayer Element property of the ucMediaPlayerControl to associate the mediaplayer.

<CODE>
public CustomizedMediaPlayer()
{
      InitializeComponent();
ucMediaPlayerControls.MediaPlayerElement = ucMediaPlayer;
}
</CODE>

Go to the Page.XAML file now. Add the code to read the initParams from the Resources and create an instance of the CustomizedMediaPlayer control.

<CODE>
Private void Page_Loaded(object sender, RoutedEventArgs e)
{
Dictionary<string, string> inputParams = new Dictionary<string, string>();
      if (App.Current.Resources["InputParams"] != null)
inputParams = App.Current.Resources["InputParams"] as Dictionary<string, string>;

      string currentSkin      = string.Empty;
      
if (inputParams.ContainsKey("Skin"))
      {
      	currentSkin = inputParams["Skin"].ToString();
Uri resourceUri = new Uri(string.Format("/SilverLightLibrary;component/Themes/{0}.xaml", currentSkin), UriKind.RelativeOrAbsolute);
            ResourceDictionary simpleStyles = new ResourceDictionary();
            simpleStyles.Source = resourceUri;
            App.Current.Resources.MergedDictionaries.Add(simpleStyles);
}

       
double height = width = 600;

if (inputParams.ContainsKey("Height"))
      {
          height = Double.Parse(inputParams["Height"].ToString());
}
      if (inputParams.ContainsKey("width"))
      {
          width = Double.Parse(inputParams["width"].ToString());
      }

//Create the customized media player.
 CustomizedMediaPlayer mediaPlayer = new CustomizedMediaPlayer();
      mediaPlayer.Name = "mediaPlayer";
mediaPlayer.Height = height;
mediaPlayer.Width = width;
      MainLayout.Children.Add(mediaPlayer);
}
</CODE>

[config4.jpg]
Figure 4

Note that the themes are loaded from the Predefined Themes folder. And also the height and width of the customized media player are set from the Initparams.

When you compile the

Silverlight

Library project (the one that has the user controls, it would create a XAP file and get copied to the ClientBin folder of the Sample Web application.

The filename would be SilvelightLibrary.xap.

Now, the missing part is the configuration that has to be provided in the InitParams collection in the html file.

Open the "SilverLightSampleTestPage html" file in the Sample project and add the following to the body tag.

<CODE>
  <div id="silverlightControlHost" style='Height:500px; Width:500px'>
<object data="data:application/x-silverlight-2," type="application/x-  silverlight-2" width="100%" height="100%">
	<param name="source" value="ClientBin/SilverLightLibary.xap"/>
	<param name="onerror" value="onSilverlightError" />
	<param name="background" value="white" />
	<param name="minRuntimeVersion" value="2.0.31005.0" />
	<param name="autoUpgrade" value="true" />
<param name="initParams" 
value="Titles=MyVideo,
MediaSource=http://tazakhobor.com/bangladeshi-tv-news/Night_News/April_2010_Tv_News/Night_News_1st_April_Banglavision.wmv" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
	</a>
	</object>
	<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
  </div>
</CODE>

Note the InitParams tag.

The screenshots below of the sample application shows the video being played with the default settings.

[video5.jpg]
Figure 5

The entire sample is provided with the article to download.

Silverlight Tooklit from CodePlex

The Silverlight toolkit from CodePlex too has a Media Player control for us to use. It comes with about 10 themes to select from. If you are running out of time, or want to just plug-and-play the mediaplayer into your application , I would suggest you to use the Toolikit.

The link is provided in the References section.

References

http://www.silverlight.net/
http://silverlight.codeplex.com/Wikipage
http://en.wikipedia.org/wiki/Microsoft_Silverlight

Related Articles





About the Author

Srinath M S

I would love to leave a footprint in this flat world

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds