Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Testing Sounds in JavaScript

You can now create a simple example that uses JavaScript to play a sound. Listing 20.1 shows an HTML document with an embedded script to play a sound when you click a button.

Listing 20.1. A Simple Example of Playing Sounds Using JavaScript

<html>
<head>
<title>Sound Test</title>
<script language="JavaScript" type="text/javascript">
function PlaySound() {
  var sound = document.getElementById("note_c1");
  try {
    // RealPlayer
    sound.DoPlay();
  } catch (e) {
    try {
      // Windows Media / Quicktime
      sound.Play();
    } catch (e) {
      alert("No sound support.");
    }
  }
}
</script>
</head>
<body>
<h1>Sound Test</h1>
<embed id="note_c1" src="c1.au" width="0" height="0"
  autostart="false" enablejavascript="true"/>
<input type="button" value="Play the Sound"
  onClick="PlaySound()">
</body>
</html>

To try the example, you'll need a sound file: the c1.au file is available at this book's website, or you can substitute the .au format sound of your choice. Load the document into a browser and click the button to play the sound.

If you don't hear a sound, or if the "No sound support" message is displayed, try looking at the JavaScript Console in Firefox or clicking the error icon in the lower-left corner of the window in Internet Explorer. You might need to install a plug-in to get it to work.

Internet Explorer might display an alert message when you load the page, as shown in Figure 20.1. Due to a patent dispute, Microsoft made their browser require you to click on something in order for embedded objects to work. Although this is only a minor annoyance in this example, it's possible to eliminate it by using JavaScript to write the <embed> tag. The Try It Yourself section of this hour includes an example of this technique.

Figure 20.1. Internet Explorer warns you before enabling an embedded object.


Try It Yourself

Playing Music with the Mouse

As an example of scripting multiple embedded objects, you can create a simple demonstration that displays a piano keyboard and plays piano notes when you click on the keys. This example requires an .au sound file for each key, which you can download from this book's website.

The HTML Document

The HTML file for this document includes a series of <div> tags that will act as the black and white piano keys. A <link> tag is used to include a CSS file to style the keys, and a <script> tag includes a script you'll create later in this section. The complete HTML document is shown in Listing 20.2.

Listing 20.2. The HTML Document for the Piano Example

<html>
<head>
<title>JavaScript Piano</title>
<link rel="stylesheet" type="text/css" href="piano.css">
</head>
<body>
<h1>JavaScript Piano</h1>
<div class="white" id="c1"> </div>
<div class="black" id="cs1"> </div>
<div class="white" id="d1"> </div>
<div class="black" id="ds1"> </div>
<div class="white" id="e1"> </div>
<div class="white" id="f1"> </div>
<div class="black" id="fs1"> </div>
<div class="white" id="g1"> </div>
<div class="black" id="gs1"> </div>
<div class="white" id="a1"> </div>
<div class="black" id="as1"> </div>
<div class="white" id="b1"> </div>
<div class="white" id="c2"> </div>
<p style="clear:left">
Click the piano keys above to play sounds.
</p>
<script language="javascript" type="text/javascript"
  src="piano.js"> </script>
</body>
</html>

Type this document or download it from this book's website and store it in the same folder as the sound files. You'll also need the CSS and JavaScript files described in the next sections.

The CSS Style Sheet

Using CSS, you can make the browser display the series of <div> tags in the HTML document as something resembling piano keys. Listing 20.3 shows the CSS file for this example.

Listing 20.3. The CSS File for the Piano Example

.white {
  float: left;
  background-color: white;
  height: 300px;
  width: 30px;
  border: 2px solid black;
}
.black {
  float: left;
  background-color: black;
  height: 225px;
  width: 25px;
}

This file defines two styles for the two classes used in the HTML document, white and black. The float attribute makes the keys appear as a horizontal set of boxes. The size of the keys is set using width and height attributes, and background-color sets the colors to differentiate the keys.

Playing the Sounds

The PlaySound() function will be called when a key is clicked to play a sound. The first lines of this function detect which key was clicked and use the id attribute of the key <div> element to construct the id attribute of the corresponding sound:

function PlaySound(e) {
  if (!e) var e = window.event;
  // which key was clicked?
  thiskey = (e.target) ? e.target: e.srcElement;
  var sound = document.getElementById("note_" + thiskey.id);

The remainder of PlaySound() will attempt to play the piano note using the try and catch routine described earlier in this hour.

Embedding the Sounds

This example will use JavaScript document.write() statements to write out an <embed> tag for each note. Although this is a roundabout way of doing things, it conveniently avoids Internet Explorer's warning dialog about embedded objects, which would otherwise pop up 13 timesonce for each embedded sound. Here are the lines that write an <embed> tag:

   document.write('<embed id="' + 'note_' + divs[i].id + '"');
   document.write(' src="' + divs[i].id + '.au" width="0"
 height="0"');
   document.write(' autostart="false" enablejavascript="true">');

The src attribute of the <embed> tag is set using the id attribute of each <div> element to embed the corresponding sound file for each key.

Putting It All Together

To get the piano working, you can combine the techniques discussed previously with a bit more JavaScript. Listing 20.4 shows the JavaScript file for this example.

Listing 20.4. The JavaScript File for the Piano Example

function Setup() {
  if (!document.getElementById) return;
  // Set up event handlers and embed the sounds
  divs = document.getElementsByTagName("div");
  for (i=0; i<divs.length; i++) {
    // embed the appropriate sound using document.write
    document.write('<embed id="' + 'note_' + divs[i].id + '"');
    document.write(' src="' + divs[i].id + '.au" width="0"
 height="0"');
    document.write(' autostart="false" enablejavascript="true">');
    // set up the event handler
    divs[i].onclick = PlaySound;
   }
}
function PlaySound(e) {
  if (!e) var e = window.event;
  // which key was clicked?
  thiskey = (e.target) ? e.target: e.srcElement;
  var sound = document.getElementById("note_" + thiskey.id);
  try {
    // RealPlayer
    sound.DoPlay();
  } catch (e) {
    try {
      // Windows Media / Quicktime
      sound.Play();
    } catch (e) {
      alert("No sound support.");
    }
  }
}
// Run the setup routine when this script executes
Setup();

The Setup() function executes when the script loads. Because the <script> tag appears after the <div> elements in the HTML file, it can set event handlers for each <div> and write out the <embed> tags. Setup() uses document.getElementsByTagName and a for loop to do this for each of the keys.

To test the piano, make sure you have everything in one folder: The HTML document, the CSS file (piano.css), the JavaScript file (piano.js), and all 13 sound files. The complete example is shown in Figure 20.2.

Figure 20.2. The JavaScript piano example in action.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Hour 19. Using Graphics and Animation
Hour 20. Working with Sound and Plug-Ins
Introducing Plug-Ins
JavaScript and Flash
Playing Sounds with JavaScript
Testing Sounds in JavaScript
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele