|
|
|
|
|
|
Author Rank:
|
|
Total page views :
39951
|
|
Total downloads :
1250
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
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#.
|
|
|
|
|
|
|
|
|
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.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from
DevExpress - Absolutely Free-of-Charge without any royalties or distribution
costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin
edit, tab control and so much more!
DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|