Click here to Skip to main content
15,881,600 members
Articles / Web Development / ASP.NET
Article

Add Multimedia Content with a Custom Control

Rate me:
Please Sign up or sign in to vote.
3.64/5 (9 votes)
6 Dec 20068 min read 60.2K   1.6K   41   11
This article describes a quick and simple approach to creating a custom web control used to display multimedia files within an ASP.NET page.

Introduction

This article describes a quick and simple approach to creating a custom web control used to display multimedia files within an ASP.NET page. Whilst the article and demonstration project are focused upon the presentation of multimedia files, the basic idea is applicable to any sort of object that you may wish to embed within an ASP.NET 2.0 page.

It is entirely possible to code the page to display multimedia files without using a custom control, having the control handy simplifies the process to the point where someone using it need only drop it onto the page and set a couple of properties within the IDE (or at runtime) to bring multimedia to the page.

At the heart of the control lies the Microsoft Windows Media Player control, and for that reason, this custom control will handle any file or streaming media source that the Media Player control itself can handle. The example provided demonstrates the use of the control to display streaming audio and video from a web cam and to display stored contents accessible through a URL.

Since the Media Player is an ActiveX control, be advised that the browser may flag the control as a security risk to the end user. The demonstration web site included in this project includes four external sources of multimedia data; two were gleaned from California’s Monterey Bay Aquarium which provides web cam feeds of several of its display areas; in the example, one control is pointed to the penguin cam and the other to the aviary cam; both are fun and interesting to look at. Also, when they are feeding and handling the penguins in front of a group, you can listen to the speaker talk about the penguins (which are from South Africa). The aviary shows different types of seashore birds in a natural environment, and it can be interesting to watch as well.

The other two controls are used to display a couple of rather odd television commercials for VW automobiles; these stored videos are made available through the popular You Tube web site (which seems to have quite a lot of odd and often humorous clips available for viewing). If you do not have a broadband connection, you may wish to consider dropping all but one of the controls from the demo page.

Image 1

Figure 1. A demonstration of four controls in simultaneous use.

Getting Started

In order to get started, open up the Visual Studio 2005 IDE and start a new project. From the new project dialog (Figure 1), under project types, select the “Windows” node from beneath “Visual Basic”, then select the “Web Control Library” template in the right hand pane. Key in “MMP” for the project and then click “OK”. (Note: all of the files are included with the project, and you may opt to use those files in lieu of recreating everything from scratch.)

Once the project has opened, right click on the solution and click on the “Add” menu option, and then select “New Item”. When the “Add New Item” dialog appears (Figure 2), select the “Web Custom Control” template; after selecting the template, key “MediaPlayer.vb” into the name field and then click “Add” to close the dialog. You may now delete the default web control that was created when the project was originally initialized from the template.

At this point, we should have an open web control library project with a single web control named “MediaPlayer.vb” in that project. One last step prior to writing the code for this project will be to add in one needed reference. To add this reference, double click on the “My Project” icon in the Solution Explorer to open “My Project”; from here, select the “References” tab, and then click the “Add” button. When the “Add Reference” dialog opens, select the .NET tab, and search down the list until you find the “System.Design” reference. Select this library, and click on the “OK” button.

Image 2

Figure 2. Visual Studio 2005 New Project Dialog

Image 3

Figure 3: Add New Item Dialog

Navigate back to the “MediaPlayer.vb” file and, at the top of the file, confirm that the project's imports match the following:

VB
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls


<ToolboxData("<{0}:MediaPlayer runat=server></{0}:MediaPlayer>")> _
Public Class MediaPlayer
    Inherits WebControl

We are now ready to add the code necessary to make this control functional. First off, we need to create some private member variables; these variables will be used to contain the path to the multimedia file and set which (if any) controls will be displayed along with the media player at runtime..

To accomplish this step, create a “Declarations” region and key in the following variable declarations:

VB
#Region "Declarations"
     Private mFilePath As String
    Private mShowStatusBar As Boolean
    Private mShowControls As Boolean
    Private mShowPositionControls As Boolean
    Private mShowTracker As Boolean

#End Region

Once the variables have been declared, we will need to provide public properties to expose the control properties to the control user; in order to accomplish this step, create a “Properties” region and key in the following code:

VB
#Region "Properties"
     <Category("Media Player")> _
    <Browsable(True)> _
    <Description("Set path to media player source file.")> _
    <Editor(GetType(System.Web.UI.Design.UrlEditor), 
    GetType(System.Drawing.Design.UITypeEditor))> _
    Public Property FilePath() As String
        Get
            Return mFilePath
        End Get
        Set(ByVal value As String)
            mFilePath = value
        End Set
    End Property


    <Category("Media Player")> _
    <Browsable(True)> _
    <Description("Show or hide the tracker.")> _
    Public Property ShowTracker() As Boolean
        Get
            Return mShowTracker
        End Get
        Set(ByVal value As Boolean)
            mShowTracker = value
        End Set
    End Property


    <Category("Media Player")> _
    <Browsable(True)> _
    <Description("Show or hide the position controls.")> _
    Public Property ShowPositionControls() As Boolean
        Get
            Return mShowPositionControls
        End Get
        Set(ByVal value As Boolean)
            mShowPositionControls = value
        End Set
    End Property


    <Category("Media Player")> _
    <Browsable(True)> _
    <Description("Show or hide the player controls.")> _
    Public Property ShowControls() As Boolean
        Get
            Return mShowControls
        End Get
        Set(ByVal value As Boolean)
            mShowControls = value
        End Set
    End Property


    <Category("Media Player")> _
    <Browsable(True)> _
    <Description("Show or hide the status bar.")> _
    Public Property ShowStatusBar() As Boolean
        Get
            Return mShowStatusBar
        End Get
        Set(ByVal value As Boolean)
            mShowStatusBar = value
        End Set
    End Property

#End Region

Note that, in the attributes section of the file path property, the code specifies an editor and further that the editor specified is defined as the URL Editor. Adding this attribute to the control specifies to the IDE how the property is to be edited; in this instance, when the control user sets the FilePath property for the control, the property grid will display a button with an ellipsis in it at the right hand side of the text box. If the user clicks on the button, the IDE will open the URL editor and will permit the user to use that editor to navigate to the multimedia file and set the FilePath property through that editor’s dialog. The control user may just key or paste the file path or URL directly into the space provided, without opening the editor. Properties set in this manner will be persisted within the control user’s project.

VB
<Editor(GetType(System.Web.UI.Design.UrlEditor), _ 
     GetType(System.Drawing.Design.UITypeEditor))>_

The remaining properties are used to set Boolean values for each media player control related options such as whether or not to show the controls at all, or to show the track bar, etc. There is no editor associated with the Boolean values but the user will be limited to supplying either True or False in the property editor.

At this point, the only thing left to do is to define how the control will be rendered. To complete this step, create a “Rendering” region and, within this region, override the RenderContents sub with the following code (note that this code was cleaned up to fit on the page, the line breaks used here will not work in the IDE):

VB
#Region "Rendering"
     Protected Overrides Sub RenderContents(ByVal writer As 
    System.Web.UI.HtmlTextWriter)

        Try

            Dim sb As New StringBuilder
            sb.Append("<object classid=clsid:" & _ 
                      "22D6F312-B0F6-11D0-94AB-0080C74C7E95 ")             
            sb.Append("codebase=http://activex.microsoft.com/activex/" & _
                      "controls/mplayer/en/nsmp2inf.cab#Version=5," & _ 
                      "1,52,701 Width = " & Width.Value.ToString() & _
                      " Height = " & Height.Value.ToString() & _
                      "type=application/x-oleobject align=absmiddle")
            sb.Append("standby='Loading Microsoft® Windows® " & _
                      "Media Player components...' id=mp1 /> ")
            sb.Append("<param name=FileName value=" & _
                      FilePath.ToString() & "> ")
            sb.Append("<param name=ShowStatusBar value=" & _
                      ShowStatusBar.ToString() & "> ")
            sb.Append("<param name=ShowPositionControls value=" & 
            ShowPositionControls.ToString() & "> ")
            sb.Append("<param name=ShowTracker value=" & 
            ShowTracker.ToString() & "> ")
            sb.Append("<param name=ShowControls value=" & 
            ShowControls.ToString() & "> ")
            sb.Append("<embed src=" & FilePath.ToString() & " ")
            sb.Append("pluginspage=http://www.microsoft.com/Windows/
            MediaPlayer type=application/x-mplayer2 ")
            sb.Append("Width = " & Width.Value.ToString() & " ")
            sb.Append("Height = " & Height.Value.ToString())
            sb.Append(" /></embed></object>")

            writer.RenderBeginTag(HtmlTextWriterTag.Div)
            writer.Write(sb.ToString())
            writer.RenderEndTag()

        Catch ex As Exception

            ' with no properties set, this will
            ' render "Custom MediaPlayer Control" in a
            ' a box on the page
            writer.RenderBeginTag(HtmlTextWriterTag.Div)
            writer.Write("Custom Media Player Control")
            writer.RenderEndTag()

        End Try

    End Sub

#End Region

Within this code, there are a few things worth looking at; first, you can see how the embedded object tag is created, and it does not take too much imagination to figure out that you can embed any valid object using this same approach. The string builder collects several variables from the control, the FilePath is passed to the object’s source, the control's height and width are also collected and passed to the object tag, and the control related properties are gathered and passed to the object’s parameters.

Having defined the contents of the object tag, the only detail remaining is to put the control on the rendered page. This is accomplished in the three lines following the definition of the string builder:

VB
writer.RenderBeginTag(HtmlTextWriterTag.Div)
writer.Write(sb.ToString())
writer.RenderEndTag()

In this example, the HTML writer is set up to place an opening Div tag; within the Div, the object defined in the string builder is written to the rendered page, and in the last line, the Div is closed.

The control is now complete. Prior to testing the control, rebuild the project. Once that has been completed and any errors encountered are repaired, it is time to test the control. To test the control, add a new web site project to the web control library project currently open (or use IIS to create a virtual directory for the included site and view that if you prefer). Once the test web site has been created, set the test project as the start up project by right clicking on the web site solution in the Solution Explorer and selecting the “Set as Start Up Project” menu option. Next, locate the Default.aspx page in the web site solution, right click on this page, and select the “Set as Start Page” menu option.

Open the Default.aspx page for editing. Locate the newly created control in the toolbox (it should be at the top) and drag the “MediaPlayer” control onto the page (Figure 4).

Image 4

Figure 4: Custom Control in Toolbox

You may now click on the object control and set its height, width, control, and file path properties. For this demo, the example webpage contains four controls, each set with valid paths to media (valid as of November 30, 2006 anyway). Looking at the IDE’s property editor, you should see each of the properties for any given control by clicking on the control:

Image 5

Figure 5: Setting the Media Player Control’s Properties in the IDE

Build the application and run it; you should now be looking at multimedia presentations on the page.

Summary

The article demonstrates the creation of a custom control; the example provided shows an approach to embedding a Windows Media Player control through a custom control as a means of simplifying the amount of work necessary to display multimedia content on an ASP.NET web page. The example code and projects were generated using ASP.NET 2.0 in Visual Studio 2005.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
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 4 Pin
JasonGarco26-Oct-10 4:23
JasonGarco26-Oct-10 4:23 
Questionhow can stop autoplay Pin
sahir1220-Apr-09 20:14
sahir1220-Apr-09 20:14 
Generalno way for windows media player Pin
noname-20138-Dec-08 8:49
noname-20138-Dec-08 8:49 
GeneralTwo Doubts Pin
dschonhals7-Jul-08 5:37
dschonhals7-Jul-08 5:37 
GeneralServer Side Event Handling Pin
clarencetroy26-Oct-07 5:15
clarencetroy26-Oct-07 5:15 
GeneralError Pin
budi wijoyo27-Sep-07 16:40
budi wijoyo27-Sep-07 16:40 
GeneralPlaying media file using Javascript Pin
AmitChampaneri19-Apr-07 1:50
AmitChampaneri19-Apr-07 1:50 
GeneralRe: Playing media file using Javascript Pin
salysle19-Apr-07 16:05
salysle19-Apr-07 16:05 
Amit:

Make sure that the tilde (~) is stripped off of the file path. If the tilde is passed to the control it will not locate the file.
GeneralRe: Playing media file using Javascript Pin
AmitChampaneri19-Apr-07 18:12
AmitChampaneri19-Apr-07 18:12 
GeneralWebCam Pin
rajpatil10-Mar-07 14:01
rajpatil10-Mar-07 14:01 
QuestionProblem with youtube videos ... Pin
mathB4-Jan-07 4:10
mathB4-Jan-07 4:10 

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.