JavaScript & Playing Sounds
 
Feature highlight: Playing audio files in JavaScript
Credit: CodeBrain


Description
Many web developers avoid using audio or sound because it appears to be complex almost requiring Flash or other plugins. Also sound can be intrusive or unwanted especially in an office setting. But then again sound can be a great alternative to color or animation for alerting users to some important change or new info. Also for some sites it can be used to trigger appropriate mood music. Finally, having a verbal explanation of what to do next can sometimes be the fastest way to explain how to use an application. By having a convenient switch off button on their web page, developers can avoid offending browser users.

Key features and JavaScript elements
This set of audio routines uses plain JavaScript such common event handlers as onClick, onMouseOver(), and onMouseOut()
along with the <embed> tag. These are the many of the same elements just seen in the JavaScript Hints/Tooltips tutorial. However, in this case the user will be primarily responsible for turning on and and off a sound recording.

What to Do

Try the three different sound playing buttons below. Click on the Play/Stop buttons, hover over the image button and do the same over the two table cells. Sounds should play and stop in all three major browsers (IE, Mozilla, and Opera) but see the warning below for some exceptional conditions. As well sound should be able to play simultaneously. Lets see the coding involved.

The Codebrain routine takes advantage of the fact that the <embed> tag allows for the normal plugin audio player to be hidden (specifying width=0 height=0 guarantees it works in all browsers). Then using onClick() and onMouseOver(), onMouseOut() events attached to the the <img> and <td> tags (it could easily have been <a>, <span>, <div> or any other tags supporting the above events) - the <embed>ed sound files are switched on and off.

Here is what to do.1) Download Sound Kit from CodeBrain. 2)Open the Cheatsheet.txt 3) Copy the audioDo() JavaScript and place within a stand alone .js file if you will use the code for many web pages; otherwise just add a inline <script> tag with the code embedded somewhere within your web pages <head></head> tags. 4) Expand the <body> tag to include onLoad="javascript:audioOn=true" which enables access to all <embed>ded audio files. 5)Add an <embed> tag for each audio file to be accessed on the web page. Here is a template: <embed name='goodasgold' src="goodasgoldshortsnip.wav" mastersound loop="false" autostart="false" autorewind="true" hidden="true" width="0" height="0">. Be sure to make autostart=false and hidden=true otherwise the sound may play immediately after loading (despite audioOnbeing set to false) or the player for the plugin will appear in the webpage (if you want to use the plugin's player then all you need is the <embed> tag and no JavaScript.

   
Hover the mouse over the image at left to play audio.
   
Hover to Play
Hover to Stop
So now we have the JavaScript routine, audioDo(), ready. The audioOn variable initialized in the <body> tag and the <embed> tags, one for each sound file initialized and located in a safe place, preferably at the end of the web page near the <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-4281076-1"); pageTracker._initData(); pageTracker._trackPageview(); </script><script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-4281076-1"); pageTracker._initData(); pageTracker._trackPageview(); </script></body> tag. So the last step is to arm the appropriate <img> <td> or other tags.

For example, in the case of the "Hover to play" and "Hover to stop" fields these are cells in a table. So the <td> tag is expanded like so <td onMouseOver="audioDo('play', 'goodasgold');"> for "Hover to Play". Correspondingly <td onMouseOver="audioDo('stop', 'goodasgold');"> is used for "Hover to Stop". For more details just right mouse lick on this tutorial and see how the <img> tags have been extended to enable sound control.

Warning

We tested these routines on a number of systems with sometimes mixed results. We could trace the problem to two sources. The audio plugins for different browsers works in some OS versions and browsers and some did not. Second, on the same OS, Windows 2000, we found that the Apple, Microsoft, and Real Players were fighting for control of which would be default application for various media and specifically audio file types. The net result is that we got mixed results as we installed and tested the full gamut of audio plugins/browser players. Many times all the 3 controls worked in all 3 browsers (IE, Mozilla, and Opera) and sometimes they partially worked, and sometimes they did not work at all. If we could give you a rational summary we would - but we can't.

Shades of the old browser wars. This situation is so shameful it makes one wish a pox on the players and specifically, Microsoft. More and more Microsoft's imperious, hardball tactics at the expense of its users and developers are once again part of the problem and not leading to quick and effective solutions. Once too often again Microsoft is becoming abusive and counterproductive in its treatment of its developers and users as it seeks to establish dominance in a market segment. Microsoft corporate, despite CEO Steve Ballmer's protestations to the contrary, has yet to learn the lesson that interoperability, compatibility and interacting well with major players is now the sine qua non of success in the IT marketplace. Getting down from the soap box; but still wary and weary of the players.

Summary

CodeBrain has provided a simple but useful set of audio routines for adding simple sound to your web pages. This does not have all the bells and whistles for .mp3, .wma, or the newer sound file types, but it does allow for basic define, start and stop controls for managing the audio side of web productions.

 
Top of Page  Tutorials Home  JavaScript References  JavaScript Books