Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ASP.NET and Web » Play Sounds on an ASP.NET Web Page

Play Sounds on an ASP.NET Web Page

This article describes a quick and easy approach to playing sound files on an ASP.NET web page in response to an event.

Author Rank :
Page Views : 52472
Downloads : 1612
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CodeForMakeNoise.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

This article describes a quick and easy approach to playing sound files on  an ASP.NET web page in response to an event.  The approach is based upon an included web custom control used to embed the sound into the web page; this control exposes a sound file path property that may be used to change the associated sound file between postbacks and in response to events fired from the web page.

The web custom control included with this article is compatible with Internet Explorer and Firefox; it has not been tested against any other browsers.  Aside from providing a demonstration of playing sounds in response to events, the included source code does provide an easy example of embedding objects in web pages by means of a web custom control; as such, the example could be used as the basis for creating other controls used to embed other types of objects into a web page.

Getting Started:

In order to get started, unzip the included source code.  Within the zip file you will note that there are two separate projects, one is the custom control itself and the other is a test website used to demonstrate the use of the control.  Create a virtual directory for the website and then open the web custom control library into the Visual Studio 2005 IDE.  If the solution does not open with the website, add the website to the solution.

The Code:  The Custom Web Control Library Project.

Within the custom web control library project (MakeNoise) you will note that there is a single custom control included (PlayPageSound.vb).  Open the class and take a look at the code; the class imports and definition were all left in their default configuration.  After the class declaration, you will note the following code in the initialization event:

Private Sub PlayPageSound_Init(ByVal sender As Object, ByVal e As

    System.EventArgs) Handles Me.Init

 

    'just to let you see it on the form

    Me.Width = 24

    Me.Height = 24

 

End Sub

This initialization code is used to set the control to 24 pixels by 24 pixels; this does not serve any purpose at runtime however at design time it provides the programmer with a box that they can click on if they need to get access to the control's properties.  It is not necessary to set the box to this size, it is only done to make it easier to manage the control at design time.  At runtime the control will not be visible to the user.

Following the initialization, the one and only property in the control is established.  The property added used to set the path to the sound file; that code looks like this:

<Category("Sound File")> _

<Browsable(True)> _

<Description("Set the location for the sound file")> _

Property SoundFile() As String

    Get

        Dim s As String = CStr(ViewState("SoundFile"))

        If s Is Nothing Then

            Return String.Empty

        Else

            Return s

        End If

    End Get

 

    Set(ByVal Value As String)

        ViewState("SoundFile") = Value

    End Set

End Property

Note that the Sound File path is set and retrieved from view state.  The attributes at the beginning of the property declaration are used to set the text in the property grid for both the category and the description areas.

The only remaining code in the control is used to establish how the page will render the control at runtime; again this is very simple and the code looks like this:

Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)

    Try

 

        Dim sb As New StringBuilder

        sb.Append("<embed src='" & SoundFile.ToString() & "'")

        sb.Append(" autostart='true' loop='false' visible='false'

        width='0' height='0' ")

        sb.Append("</embed>")

 

        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        writer.Write(sb.ToString())

        writer.RenderEndTag()

 

    Catch ex As Exception

 

        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        writer.Write("PlayPageSound Control")

        writer.RenderEndTag()

 

    End Try

 

End Sub

The overridden Render Contents subroutine uses a string builder to piece together the code used to embed the sound into the page.  In this instance, only the string pointing to the location of the sound file is changed based upon the current contents of the Sound File property; however, using this same approach one could add other properties such a Loop, Visible, Auto-start, Height and Width and then set them in a manner consistent with what is shown here for setting the sound file property.  Given this configuration, the control will not display a visible UI during the sound's playback.  If one were to set the control to be visible and then give some height and width dimension, the control will display a media player interface to the user whenever the sound is playing.  If the UI were made visible, in Internet Explorer, the Microsoft Media Player control's interface would be displayed, in Firefox, the Quick Time player interface would be shown.

Once the emded tag is created, the  HTML Text Writer is used to place the embed tag within a div.  If anything were to go wrong and an exception was thrown, the catch block will capture the exception and  the HTML Text Writer is then used to write the name of the control onto the page.

The Code:  The Test Web Site.

Open up the test web site; notice that the site consists of a single web page (default.aspx).  The site is setup to simulate an online test; to that that end, the page displays three questions to the user, keeps track of the number of correct responses, and displays messages to the user whenever the user answers a question correctly or incorrectly, and it plays a sound whenever the user gets an answer correct and a different sound whenever the user misses the answer.

This web page contains a single instance of the Play Page Sound custom control.  Depending upon whether or not a user clicks on the right answer or the wrong answer, the control's Sound Path property is set to play the appropriate sound.  Each radio button list (used to show the user the answer options) has its AutoPostBack property set to true so that the correct sound will load and play in response to the user's selection.  If you did not set the AutoPostBack property to true, the sound would not play until some other event called a post back.

Take a quick look at the handler associated with an selected index changed to one of the radio button lists:

Protected Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged

 

        If RadioButtonList1.SelectedIndex = 2 Then

            Me.PlayPageSound1.SoundFile = "applaus8.wav"

            lblStatus.Text = "<b>That's Right!</b>"

        Else

            Me.PlayPageSound1.SoundFile = "burp.wav"

            lblStatus.Text = "<b>You missed that one, try it again</b>"

        End If

 

        EvaluateResponses()

End Sub

In this instance, the third answer in the list is correct and the other three options are incorrect.  Whenever the user selects the correct response, the Play Page Sound control's Sound File property is set to a wave file called "applaus8.wav".  In all other options, the Sound File property is set to a wave file called "burp.wav".  After setting the sound to point at the correct wave file, a call is made to a subroutine called, "EvaluateResponses()".  This subroutine looks like this:

Private Sub EvaluateResponses()

 

    Dim correct As Integer = 0

 

    If Me.RadioButtonList1.SelectedIndex = 2 Then

        correct += 1

    End If

 

    If Me.RadioButtonList2.SelectedIndex = 3 Then

        correct += 1

    End If

 

    If Me.RadioButtonList3.SelectedIndex = 1 Then

        correct += 1

    End If

 

    Me.lblResponses.Text = correct.ToString() & " of 3 Answered

    Correctly."

 

End Sub

As you can see, this subroutine checks each radio button list to see if the correct item has been selected and for each correct response on the page, it updates an integer variable  called "correct" to contain that list.  After calculating the score, the integer variable is used to update the text used to display the number of correct responses made.

That pretty much covers it, the web page in operation looks like this:


 
Figure 1:  Test Web Site In Operation

Summary.

This article discussed a simple method that may be used to bring sound to a web site through the use of a custom control.  There are other available methods including pure JavaScript methods that will do the same thing.  This approach demonstrates using a post-back event as the basis for loading and playing a new sound, if you need or want to play sounds without the post-back, then you should look to the pure JavaScript approaches. 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
How to Play a Soundfile in a subdirectory / How to create and then play or trigger postback. by Ed On February 3, 2009
Scott, Excellent article. It has really helped me a lot. I'm trying to get something to work and after almost a week, thought I'd simply ask. Suppose src file is in a directory off the root. How would you set the path. Although I set it to a file that exists, it simply won't play no matter what I try. (e.g. Ive tried filename = "App_Data/playfile.wav", Server.MapPath("app_data/playfile.wav") If I move the file back to the application root it works / plays when the page is loaded. Because of item 2, I don't want my users to have R/W privledges to my application root. Secondly, my real objective is to create the file that I want to play by making a selection from a GridView record. In this case, Soundfile is saved as a byte stream in a record of my database. When I select the record, I have it writing a file to the App_data subdirectory. (overwrites playfile.wav) I then attempt to set the PlayPageSound to that same file again. Either Gridview doesn't trigger a postback or file does not exist yet or get recongnized as existing. Anyidea's of how to make this work? Afterward, file was written cause I can play it back.
Reply | Email | Modify 
Re: How to Play a Soundfile in a subdirectory / How to create and then play or trigger postback. by Scott On February 4, 2009

Setting up a sounds folder and placing some wav files in it; I ran this code which executed without error.

   PlayPageSound1.SoundFile = "sounds/r2d2_01.wav"

Reply | Email | Modify 
Re: How to Play a Soundfile in a subdirectory / How to create and then play or trigger postback. by Ed On February 4, 2009

Sorry,

I tried it again and turns out that the problem was that the contents of App_Data folder was not accessible.  I moved the wav files to a regular "new" folder and think it is working now. 

Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.