audio> controlsstudents.cypresscollege.edu/cis261/lc10.pdfPenn P. Wu, PhD 280 In case of Windows...
Transcript of audio> controlsstudents.cypresscollege.edu/cis261/lc10.pdfPenn P. Wu, PhD 280 In case of Windows...
Penn P. Wu, PhD
278
Lecture #10 Applying sound effects
HTML5 <audio>
tag
With the HTML5 <audio> tag, you can insert a sound file, such as a MP3 file, on a web
page. Then, write appropriate JavaScript code to control the default HTML5 audio player.
It is necessary to note that any browser that does not support HTML5 will not recognize
this <audio> tag. The audio element enables you to fall back with an error message or
another playback technology if the user’s browser does not support the HTML5 audio
element, as would be the case with older browsers. The following is a very simple HTML5
code that creates an interface to play a sound file named “u1.mp3”. By the way, the
controls attribute forces the browser to display an interface to control the sound file.
<!DOCTYPE html>
<html>
<body>
<audio src="u1.mp3" controls></audio>
</body>
</html>
The output looks:
The <audio> tag also supports XHTML format; therefore, the above statement can be
simplified to the following:
<audio src="u1.mp3" controls />
The following is a simple code that demonstrates how to load a MP3 file and play it
automatically. Notice the “autoplay” attribute which is used to play the sound
automatically. The audio element is added directly to your HTML code, using the “src”
property to specify the audio file to play. The “autoplay” property tells the browser to
immediately load and play the audio file after the audio object is loaded.
<!DOCTYPE html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
</head>
<body>
<audio src="u1.mp3" autoplay controls></audio>
</body>
</html>
To tackle with possible incompatible issues, you may want to add the optional <meta
http-equiv-"X-UA-Compatible" content="IE=11" /> to the <head> block of a
webpage to force Windows Internet Explorer 11 to use the latest standards.
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
</head>
According to Microsoft, when using the X-UA-Compatible tag, it should be as high as
possible in your document head: “If you are using the X-UA-Compatible META tag you
want to place it as close to the top of the page’s HEAD as possible. Internet Explorer
Penn P. Wu, PhD
279
begins interpreting markup using the latest version. When Internet Explorer encounters the
X-UA-Compatible META tag it starts over using the designated version's engine. This is a
performance hit because the browser must stop and restart analyzing the content.” By the
way, the following is a list of your options.
"IE=edge"
"IE=11"
"IE=EmulateIE11"
"IE=10"
"IE=EmulateIE10"
"IE=9"
"IE=EmulateIE9
"IE=8"
"IE=EmulateIE8"
"IE=7"
"IE=EmulateIE7"
The following table lists attributes of <audio> defined in HTML5.
Attribute Valid value Description
autoplay autoplay Specifies that the audio will start playing as soon as it is
ready
controls controls Specifies that audio controls should be displayed (such as a
play/pause button etc)
loop loop Specifies that the audio will start over again, every time it is
finished
muted muted Specifies that the audio output should be muted
preload auto,
metadata,
none
Specifies if and how the author thinks the audio should be
loaded when the page loads
src URL Specifies the URL of the audio file
The “preload” attribute is used in the audio element for buffering large files. It can take
one of 3 values:
"none" does not buffer the file
"auto" buffers the media file
"metadata" buffers only the metadata for the file
The following demonstrates how to automatically loads the sound file. By the way, the
controls attribute forces the browser to display the standard HTML5 controls for the audio
on the web page.
<audio src="audio.mp3" preload="auto" controls></audio>
The “loop” property allows you to continuously play the MP3 file. The loop attribute
continuously replays the sound file from the beginning. If you do not need any of the
intrinsic controls, do not use the attributes. The autoplay attribute is a Boolean attributes. It
only accept true or false as value. By default, its value is false. Interestingly, It seems to
work fine by setting autoplay="autoplay".
<audio src="u1.mp3" autoplay loop></audio>
Most of the browsers come with a default sound player interface which allows users to
control the volume, play and pause the sound file. To display this default interface, use the
“controls” property as shown below.
<audio src="u1.mp3" controls></audio>
Penn P. Wu, PhD
280
In case of Windows Internet Explorer, the audio element displays a simple player that has
basic play, pause, position slider, and volume controls, as shown below. The player also
displays the playing time, and the time left in the file. If you hover over either time display,
you can skip forward or backward by 30 seconds.
Interestingly, most of the games do not need the interface, anyway; therefore, it may not be
a good practice to display the interface. The following omits the use of controls attribute;
therefore, the above interface will not be displayed.
<audio src="u1.mp3"></audio>
By the way, the muted attribute is a Boolean attribute which indicates whether the audio
will be initially silenced. Its default value is false. The following demonstrates how to set
the sound output to “muted”.
<audio src="u1.mp3" autoplay controls muted></audio>
Multiple source files can be specified using the <source> element in order to provide video
or audio encoded in different formats for different browsers. The above code may be
broken down to the following if you wish to support more than one file type. Notice that
the following code also specifies the MIME type which can help the browser to localize the
sound files.
<audio controls>
<source src="u1.mp3" type="audio/mpeg">
<source src="u1.ogg" type="audio/ogg">
</audio>
Beginning with Internet Explorer 11/10/9, any audio or video content needs the correct
mime type set on the server, or the files won't play. Internet Explorer supports MP3 audio,
and MP4 audio and video. The following table shows the required settings for your web
server to host these files correctly.
Media file to serve Extension setting Mime type setting
Audio mp3 mp3 audio/mpeg
Audio mp4 m4a audio/mp4
The <audio> tag also support the Ogg video file (.ogv), such as:
<source src="SampleVideo.ogv" type="video/ogv">
In this lecture, the focus is placed on the sound file. The instructor chooses to use .mp3
files. Therefore, the code should be similar to the following.
<source src="u1.mp3" type="audio/mpeg">
The codec attribute of <audio> tag specifies the device or program that compresses sound
data to enable faster transmission and decompresses received sound data.The following
demonstrates how to specify the codec; however, this lecture only use generic .mp3 sound
file. It is not necessary to specify the codec.
<audio>
<source src="u1.mp3" type='audio/mpeg; codecs="mp3"'>
<source src="u1.oga" type='audio/ogg; codecs="vorbis"'>
</audio>
Penn P. Wu, PhD
281
Indentifying a
sound file object
The <audio> tag support the “id” attribute. By embedding a sound file to an HTML file
using the <audio> tag, JavaScript programmers can use the
document.getElementById() method to identify the sound file object. The following
demonstrates how it works.
var s1 = document.getElementById("s1");
............
<audio id="s1" src="u1.mp3"></audio>
The following is the complete code.
<!DOCTYPE html>
<html>
<script>
function playIt()
{
var s1 = document.getElementById("s1");
s1.play();
}
</script>
<body>
<audio id="s1" src="u1.mp3"></audio>
<p><button onClick="playIt()">Play</button></p>
</body>
</html>
The following is another example that demonstrates how to identify a sound file object and
then either mute or unmute the sound. The muted property of <audio> tag sets or returns
whether the audio should be muted (sound turned off).
<!DOCTYPE html>
<html>
<script>
function muteIt()
{
var s1 = document.getElementById("s1");
s1.muted = true;
}
function unMuteIt()
{
var s1 = document.getElementById("s1");
s1.muted = false;
}
</script>
<body>
<audio id="s1" src="u1.mp3" autoplay preload
controls></audio>
<p><button onClick="muteIt()">Mute</button></p>
<p><button onClick="unMuteIt()">Unmute</button></p>
</body>
</html>
Another way to idenfiy the sound file object is to use the
document.getElementsByTagName() method, as shown below. However, the
getElementsByTagName() method returns a collection of all elements in the document with
Penn P. Wu, PhD
282
the specified tag name, as a NodeList object. The NodeList object represents a collection of
nodes. The nodes can be accessed by index numbers. The index starts at 0. It is relatively
complicated to use the getElementsByTagName() method to identify the sound file. The
instructor chooses to only use the document.getElementById() method in this lecture.
var s1 = document.getElementsByTagName("s1")[0];
s1.play();
The following demonstrates how to detect an element’s ID by using the
document.getElementById() method.
<!DOCTYPE html>
<html>
<script>
function playIt(event)
{
var p1 = document.getElementById('p1');
p1.innerHTML = event.target.id;
}
</script>
<body>
<p id="p1"></p>
<p><button id="b1" onClick="playIt(event)">Play</button></p>
</body>
</html>
JavaScript code to
control sound files
Controlling a HTML5 audio player with JavaScript is pretty easy. The HTML5 DOM
provided the following methods and events for the <audio>: play() and pause().The
play() method starts playing the current audio or video. The pause() method pauses the
current audio or video.
var s1 = document.getElementById("s1");
s1.play();
............
<audio id="s1" src="u1.mp3"></audio>
To use the audio element with JavaScript, it is necessary to define an audio tag with an
“id”. The following example shows how you can build an audio player. The audio object is
identified with document.getElementById() mehod. The play() function loads and starts
playback of a media resource. The pause() function pauses the current playback and sets
paused to TRUE.
<!DOCTYPE html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
</head>
<body>
<audio id="u1" src="u1.mp3"></audio>
<div>
<button onclick="document.getElementById('u1').play()">Play
</button>
<button
onclick="document.getElementById('u1').pause()">Pause
</button>
Penn P. Wu, PhD
283
</div>
</body>
</html>
The following is another example that demonstrates how you can use an event (such as
“onkeydown”) and an event handle to play the sound file on demand.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
<script type="text/javascript">
function playAudio()
{
var u1 = document.getElementById('u1');
u1.play();
}
document.onkeydown = playAudio;
</script>
</head>
<body>
<audio id="u1" src="u1.mp3" preload="auto"></audio>
</body>
</html>
The window.HTMLAudioElement property can help to check if the browser supports
<audio> element. In the following code, no code is executed if the audio element is not
supported.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
<script type="text/javascript">
function playIt()
{
if (window.HTMLAudioElement)
{
var u1 = document.getElementById('u1');
u1.play();
}
else
{
window.alert("Your browser does not support HTML
audio.");
}
}
document.onkeydown = playIt;
</script>
</head>
<body>
<audio id="u1" src="u2.mp3" preload="auto"></audio>
Penn P. Wu, PhD
284
</body>
</html>
The volume property gets or sets the volume level for audio portions of the media element.
The following demonstrates how to use the volume property to set the initial volume to
0.5. By the way, the current playback volume as a number in the range of 0.0 to 1.0 which
represents quietest to loudest volume. The code also demonstrates how to use two buttons
to increase and decrease the sound volume.
<!DOCTYPE html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
<script>
function init()
{
var s1 = document.getElementById("s1");
s1.volume=0.5;
}
window.onload = init;
</script>
</head>
<body>
<audio id="s1" src="u1.mp3" autoplay controls></audio>
<p>
<button onclick="document.getElementById('s1').volume+=0.1">
Increase Volume</button>
<button onclick="document.getElementById('s1').volume-=0.1">
Decrease Volume</button>
</p>
</body>
</html>
The currentTime property gets or sets the current playback position, in seconds. There is
no function, to the best knowledge of the instructor, that can terminate the playback.
However, the pause() can possible help to stop the sound file with some arrangements.
Basically, the arrangement could be as simple as an individual function that uses pause()
and currentTime.
function stopIt()
{
var u1 = document.getElementById('u1');
u1.pause();
u1.currentTime = 0;
}
The following demonstrates how to use play(), pause(), and currentTime to control the
sound effect of a simple slot machine game. When the player presses a key on the
keyboard, the play() function begins the playback of “u1.mp3”. When the speed of
setTimeout() method reaches 250 milliseconds, the pause() function takes effect and the
currentTime property resets the playback position to 0 seconds which is of couse the
beginning of the sound file.
<!DOCTYPE html>
<html>
<head>
Penn P. Wu, PhD
285
<style type="text/css">
span {
position: absolute;
border: 2px solid black;
width: 40px;
height: 40px;
font-size:36px;
text-align: center;
color: red;
}
</style>
<script type="text/javascript">
var speed = 200; // for the spin speed
var i = -5; // force speed to descrement; faster
var s1;
function spin()
{
var n1 = Math.floor(Math.random()*10);
var n2 = Math.floor(Math.random()*10);
var n3 = Math.floor(Math.random()*10);
document.getElementById("b1").innerText = n1;
document.getElementById("b2").innerText = n2;
document.getElementById("b3").innerText = n3;
if (speed==10)
{
i = 5; // force speed to increment; slower
}
if (speed > 250)
{
document.getElementById('u1').pause();
document.getElementById('u1').currentTime=0;
clearTimeout(s1);
speed = 200;
i = -5;
}
else {
s1 = setTimeout("spin()", speed); // time out rate
}
speed += i; //increment or decrement
}
function start()
{
spin();
document.getElementById('u1').play();
}
</script>
</head>
<body>
<span id="b1" style="left:10px; top: 10px"></span>
<span id="b2" style="left:60px; top: 10px"></span>
<span id="b3" style="left:110px; top: 10px"></span>
Penn P. Wu, PhD
286
<button onClick="start()" style="position:absolute;
left:180px; top: 10px">Spin</button>
<audio id="u1" src="u1.mp3"></audio>
</body>
</html>
The following example uses the setTimeout() method to play the sound file for only 3
seconds.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function playIt()
{
var u1 = document.getElementById('u1');
u1.play();
var s1 = setInterval("stopIt()", 3000);
}
function stopIt()
{
var u1 = document.getElementById('u1');
u1.pause();
u1.currentTime = 0;
}
document.onkeydown = playIt;
</script>
</head>
<body>
<audio id="u1" src="u1.mp3" preload="auto"></audio>
</body>
</html>
You can get details about the <audio> element at http://msdn.microsoft.com/en-
us/library/hh772923(v=vs.85).aspx.
Change the source
of sound file.
Once the sound file object is identified, programmers can use the following code to assign a
valid file path to the src attribute, use the load() method to load the sound file, and then use
the play() method to play the new sound file. The load() method resets the audio or video
object and loads a new media resource.
var s1 = document.getElementById("s1");
s1.src = "u2.mp3";
s1.load();
s1.play();
............
<audio id="s1" src="u1.mp3"></audio>
The following is the complete code that demonstrates how to change the sound file. By
clicking the button, the sound file changes from “u1.mp3” to “u2.mp3”.
<!DOCTYPE html>
<head>
<meta http-equiv-"X-UA-Compatible" content="IE=11" />
Penn P. Wu, PhD
287
<script>
function changeIt()
{
var s1 = document.getElementById("s1");
s1.src = "u2.mp3";
s1.load();
s1.play();
}
</script>
</head>
<body>
<audio id="s1" src="u1.mp3" autoplay controls></audio>
<p><button onClick="changeIt()">Change</button></p>
</body>
</html>
Intgerating sound
effects to a game
The integration is actually the embedding of sound files to an HTML5 file using the
<audio> tag, and then programmatically controlling the embedded sound file. In the
following example, the <audio> tag embeds a sound file. The playsound() function is then
added to control the sound file by using the play() method to play the sound. The
playsound() method is later called when a specific condition is made.
...............
function check()
{
....................
{
playsound();
ap01.src="explode.gif";
setTimeout("ap01.style.display='none'",1000);
}
}
function playsound()
{
document.getElementById('explosion').play();
}
...............
<audio id="explosion" src="explosion.mp3"
preload="auto"></audio>
In the following example, the instructor uses the preload attribute of the <audio> tag to
load the sound file when the HTML page is loaded, then uses the autoplay attribute to
automatically play the sound file endlessly after the page is loaded. Consequently, the
“circusride.mp3” file becomes the background sound file of the game.
<audio id="circusride" preload="auto" autoplay="autoplay"
loop="loop">
<source src="circusride.mp3">
</audio>
In the following example, the stopIt() method uses the pause() method to halt the
currently playing sound file. It also uses the currentTime attribute to force the media play
to return to the beginning of the sound file by setting the value of currentTime to 0.
function stopIt()
{
Penn P. Wu, PhD
288
clearTimeout(timer1);
document.getElementById('jeopardy').pause(); // pause
// reset to beginning
document.getElementById('jeopardy').currentTime = 0;
}
.................
<audio id="jeopardy" src="jeopardy_short.mp3"
preload="auto"></audio>
Some games require programmers to stop loading of sound file based on a given condition.
While stopping the playback of a sound file is as easy as calling the element's pause()
method, the browser only keeps downloading the sound file until the media element is
disposed of through garbage collection. The following demonstrates how to
programmatically stops the downloading of a long sound file.
var s1 = document.getElementById("s1");
s1.pause();
s1.src='';
Another option is to call the removeAttribute() method to remove the “src” attribute from
the <audio> tag.
var s1 = document.getElementById("s1");
s1.pause();
s1.removeAttribute("src");
By removing the sound file object's src attribute or setting it to an empty string, you can
permanently destroy the sound file object's internal decoder, which stops the network
download.
Review Questions 1. Which property of the <audio> element is used to play the sound automatically?
A. playauto
B. autoplay
C. auto
D. play="auto"
2. Given the following code segment, which can play the sound file?
<audio id="u1" src="u1.mp3" autoplay></audio>
A. document.getElementByClassName('u1').play();
B. document.srcElementBy('u1').play();
C. document.getElementById('u1').play();
D. document.getElementByTagName('u1').play();
3. Which one can possibly force the browser to display a user interface for control the
sound file?
A. <audio src="u1.mp3" ui="true"></audio>
B. <audio src="u1.mp3" controls></audio>
C. <audio src="u1.mp3" uis="true"></audio>
D. <audio src="u1.mp3" control="true"></audio>
4. Which can set the sound file to be silent by default, regardless how it is loaded to the
media player?
A. <audio src="u1.mp3" playmode="mute"></audio>
B. <audio src="u1.mp3" sound="mute"></audio>
C. <audio src="u1.mp3" autoplay="muted"></audio>
Penn P. Wu, PhD
289
D. <audio src="u1.mp3" muted></audio>
5. Given the following statement, which can successfully identify the "g1" sound file object
in a JavaScript function and then use the play() method to play back the sound?
<audio src="u1.mp3" id="g1"></audio>
A. var g1 = document.getElementById('g1'); g1.play();
B. var g1 = document.getElementById("g1").[0]; g1.play();
C. document.getElementById("g1").[0].play();
D. document.getElementById('g1'); g1.[0].play();
6. Given the following statement, which can temporarily halt the playing sound file object
"g1" from a button clicking?
<audio src="u1.mp3" id="g1"></audio>
A. <button onclick="document.getElementById('g1').[0].stop()">Stop</button>
B. <button onclick="document.getElementById('g1').pause()">Pause</button>
C. <button onclick="document.getElementById('g1').[0].halt()">Halt</button>
D. <button onclick="document.getElementById('g1').hold()">Hold</button>
7. Given the following statement, which can set the default volume of "g1" sound file
object to 0.5, assuming "g1" has been properly identified?
A. g1.volume=0.5;
B. g1.volume+=0.5;
C. g1.volume-=0.5;
D. g1.volume==0.5;
8. Given the following statement, which can change the sound file object's source from
"u1.mp3" to "u2.mp3" and play the new sound file, assuming "g1" has been properly
identified?
<audio src="u1.mp3" id="g1"></audio>
A. g1.path = "u2.mp3"; g1.reload(); g1.play();
B. g1.file = "u2.mp3"; g1.load(); g1.replay();
C. g1.src = "u2.mp3"; g1.load(); g1.play();
D. g1.get("u2.mp3"); g1.load(); g1.play();
9. When click the following button, which sound file will be played?
<button onClick="document.getElementById('E').play()">Play
</button>
A. <audio id="E" src="E.mp3" muted />
B. <audio id="E" src="E.mp3" preload="auto" />
C. <audio id="E" src="E.mp3" volume=0 />
D. <audio src="E.mp3" preload="auto" />
10. Given the followign code, which allows you to fast forwards to the 15 seconds
position?
<audio id="u1" src="u1.mp3"></audio>
A. document.getElementById('u1').currentTime += 15.0;
B. document.getElementById('u1').currentTime = 15.0;
C. document.getElementById('u1').currentTime -= 15.0;
Penn P. Wu, PhD
290
D. document.getElementById('u1').currentTime != 15.0;
Penn P. Wu, PhD
291
Lab #10 Sound Effects
Preparation #1:
1. Create a new directory named C:\games.
2. Use Internt Explorer to go to http://students.cypresscollege.edu/cis261/download.htm to download lab10.zip
(a zipped) file. Extract the files to C:\games directory.
Learning Activity #1:
1. Change to the C:\games directory.
2. Locate the lab9_4.htm file you created in the previous lecture, make a copy of it, and then renamed the copied
file to lab10_1.htm.
3. Use Notepad to open the C:\games\lab10_1.htm file.
4. Add the following bold-faced lines:
...............
...............
function check()
{
if ((parseInt(b01.style.left) >= parseInt(ap01.style.left)) &&
(parseInt(b01.style.left) <= parseInt(ap01.style.left) + 70) &&
(parseInt(b01.style.top) <= parseInt(ap01.style.top) + 70))
{
playsound();
ap01.src="explode.gif";
setTimeout("ap01.style.display='none'",1000);
}
}
function playsound()
{
document.getElementById('explosion').play();
}
window.onload = function()
..................
..................
<body id="bd" bgcolor="black">
<img id="ap01" src="e_plan.gif" style="position:absolute; z-index:3">
<img id="st01" src="shooter.gif" style="position: absolute;
top:300px; left:100px">
<span id="b01" style="position:absolute; color:white; display:none; z-
index:2">!</span>
<audio id="explosion" src="explosion.mp3" preload="auto"></audio>
<audio id="engine" autoplay="autoplay" preload="auto" loop="loop">
<source src="engine.mp3">
</audio>
</body>
</html>
5. Test the program. Whenever you hit the enemy’s plan, the explosion.mp3 sound file is played.
Penn P. Wu, PhD
292
6. Download the “assignment template”, and rename it to lab10.doc if necessary. Capture a screen shot similar to
the above one and then paste it to a Micrsoft Word document named lab10.doc (or .docx).
Learning Activity #2: Gun shot
1. In the C:\games directory, use Notepad to create a new file named C:\games\lab10_2.htm with the following
contents:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var i = 95; // declare a variable i
function shoot()
{
var b01 = document.getElementById('b01');
b01.style.display='inline';
if (i >= 400)
{
b01.style.display='none';
i=95;
s1 = clearTimeOut(s1);
}
else
{
i += 10; // i increment by 10
}
b01.style.pixelLeft = i + "px"; //let the current x-coordinate equal i value
var s1 = setTimeout("shoot()", 20); // call shoot() after 20 milliseconds
}
function playsound()
{
document.getElementById('gunshot').play();
}
document.onkeydown = function()
{
playsound();
shoot();
}
</script>
</head>
Penn P. Wu, PhD
293
<body>
<img src="gun.gif">
<img src="bullet.gif" id="b01" style="position:absolute; display:none; top:20px;
left:95px"></span>
<audio id="gunshot" src="gunshot.mp3" preload="auto"></audio>
</body>
</html>
2. Test the program. Press any key to fire the gunshot; you should hear the sound effect, too. A sample output
looks:
3. Capture a screen shot similar to the above one and then paste it to a Micrsoft Word document named lab10.doc
(or .docx).
Learning Activity #3: Squeeze the clown
1. In the C:\games directory, use Notepad to create a new file named C:\games\lab10_3.htm with the following
contents:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var k=1;
function init()
{
var bar = document.getElementById('bar');
var clown = document.getElementById('clown');
clown.style.top = (parseInt(bar.style.top) - parseInt(clown.style.height)) + "px";
}
function goUp()
{
var bar = document.getElementById('bar');
var clown = document.getElementById('clown');
if (parseInt(clown.style.top) <= 20)
{
clown.style.top = "20px"; // fix clown's y-coordinate, so it won't move
clown.style.height = (parseInt(bar.style.top) - 20) + "px"; //fix clown's height
if (parseInt(clown.style.width) >= 100)
{
clown.style.width = "100px"; // fix clown width
}
Penn P. Wu, PhD
294
else
{
clown.style.width = (parseInt(clown.style.width) + 2) + "px"; // increase clown
width
}
document.getElementById('hit').play();
}
else
{
clown.style.top = (parseInt(bar.style.top) - parseInt(clown.style.height)) +
"px";
bar.style.height = k + "px";
}
if ( parseInt(bar.style.top) >= 20 && k!=1)
{
bar.style.top = (parseInt(bar.style.top) - 5) + "px";
}
k += 5;
}
window.onload = function()
{
init();
}
document.onkeydown = function()
{
goUp();
}
</script>
</head>
<body>
<span style="position:absolute; left:10px; top:0px; background-color:red;
width:100px; height:20px"></span>
<img id="clown" src="clown.jpg" style="position: absolute; left:20px; width:54px;
height:120px;">
<span id="bar" style="position: absolute; left:10px; top:280px; background-color:
red; width:100px; height:1px;"></span>
<audio id="hit" src="hit.mp3" preload="auto"></audio>
<audio id="circusride" preload="auto" autoplay="autoplay" loop="loop">
<source src="circusride.mp3">
</audio>
</body>
</html>
2. Test the program. When the page is loaded, the background music plays. When squeezing the clown, you will
hear a sound effect. A sample output looks:
Penn P. Wu, PhD
295
3. Capture a screen shot similar to the above one and then paste it to a Micrsoft Word document named lab10.doc
(or .docx).
Learning Activity #4
1. In the C:\games directory, uUse Notepad to create a new file named C:\games\lab10_4.htm with the following
contents:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<style>
span { text-align: center; }
</style>
</head>
<script>
var timer1;
var code = "";
function createBoard()
{
var j = 0;
for (i = 0; i< 100; i++)
{
code += "<span id='s" + i + "' style='width: 25px; height: 25px; border: 1px
solid black; position: absolute; left:" + (10+(i%10)*25) + "px; top:" + (10+j*25) +
"px'>" + i + "</span>";
if (i%10==9) { j++; }
}
var p1 = document.getElementById("p1");
p1.innerHTML = code;
}
var n;
function startIt()
{
clearTimeout(timer1);
n = Math.floor(Math.random() * 99);
markIt();
playsound();
}
Penn P. Wu, PhD
296
function markIt()
{
clearIt();
n = n + 1;
n = (n % 100);
var s1 = document.getElementById("s"+ n);
s1.style.backgroundColor = "yellow";
var p2 = document.getElementById("p2");
p2.innerHTML = n;
timer1 = setTimeout("markIt()", 50);
}
function clearIt()
{
for (i=0; i<100; i++)
{
var s1 = document.getElementById("s"+ i);
s1.style.backgroundColor = "white";
}
}
function stopIt()
{
clearTimeout(timer1);
document.getElementById('jeopardy').pause(); // pause
document.getElementById('jeopardy').currentTime = 0; // reset
}
function playsound()
{
document.getElementById('jeopardy').play();
}
window.onload = createBoard;
</script>
<body>
<div id="p1"></div>
<p id="p2" style="left: 300px; top:10px; position: absolute; font-size: 14px;
font-family:arial; color: red"></p>
<button id="b1" style="width:100px; left: 300px; top:120px; position: absolute"
onclick="startIt()">Start</button>
<button id="b2" style="width:100px; left: 300px; top:160px; position: absolute"
onclick="stopIt()">Stop</button>
<audio id="jeopardy" src="jeopardy_short.mp3" preload="auto"></audio>
</body>
</html>
2. Test the program. A sample output looks:
Penn P. Wu, PhD
297
3. Capture a screen shot similar to the above one and then paste it to a Micrsoft Word document named lab10.doc
(or .docx).
Learning Activity #5: Piano
1. In the C:\games directory, use Notepad to create a new file named C:\games\lab10_5.htm with the following
contents:
<!-- Microsoft Edge, IE10/11, FireFox, Chrome -->
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wKey {
position: absolute;
top: 20px;
background-color: white;
border-top: 1px solid #cdcdcd;
border-left: 1px solid #cdcdcd;
border-bottom: 4px solid #cdcdcd;
border-right: 1px solid black;
height: 150px;
width: 40px;
}
.bKey {
position: absolute;
top: 20px;
background-color: black;
border: 1px solid white;
height: 70px;
width: 36px;
}
</style>
<script type="text/javascript">
var keyID; // global variables
var soundId;
function playMe(e)
{
keyID = ""; // clear memory
soundId = "";
if (!e) { var e = window.event; }
Penn P. Wu, PhD
298
if (e.shiftKey) // shift key is boolean
{
switch (e.keyCode)
{
case 67: soundId = "cs0"; keyID="cSharp"; break; //shift+C
case 68: soundId = "ds0"; keyID="dSharp"; break; //shift+D
case 70: soundId = "fs0"; keyID="fSharp"; break; //shift+F
case 71: soundId = "gs0"; keyID="gSharp"; break; //shift+G
case 65: soundId = "as0"; keyID="aSharp"; break; //shift+A
}
}
else
{
switch (e.keyCode)
{
case 65: soundId = "a0"; keyID = "midA"; break; //A
case 66: soundId = "b0"; keyID = "midB"; break; //B
case 67: soundId = "c0"; keyID = "midC"; break; //C
case 68: soundId = "d0"; keyID = "midD"; break; //D
case 69: soundId = "e0"; keyID = "midE"; break; //E
case 70: soundId = "f0"; keyID = "midF"; break; //F
case 71: soundId = "g0"; keyID = "midG"; break; //G
}
}
document.getElementById(soundId).play(); //play sound
Down(keyID);
}
function Down(keyID) {
document.getElementById(keyID).style.borderTop="1px solid black";
document.getElementById(keyID).style.borderLeft="1px solid black";
document.getElementById(keyID).style.borderBottom="1px solid black";
document.getElementById(keyID).style.borderRight="1px solid #cdcdcd";
}
function Up(keyID) {
document.getElementById(keyID).style.borderTop="1px solid #cdcdcd";
document.getElementById(keyID).style.borderLeft="1px solid #cdcdcd";
document.getElementById(keyID).style.borderBottom="4px solid #cdcdcd";
document.getElementById(keyID).style.borderRight="1px solid black";
document.getElementById(soundId).pause();
document.getElementById(soundId).currentTime = 0; // reset
}
document.onkeydown = function()
{
playMe();
}
document.onkeyup = function()
{
Up(keyID);
}
</script>
</head>
<body>
<div>
<span class="wKey" id="midC" style="left: 50px"></span>
<span class="wKey" id="midD" style="left: 91px"></span>
Penn P. Wu, PhD
299
<span class="wKey" id="midE" style="left: 132px"></span>
<span class="wKey" id="midF" style="left: 173px"></span>
<span class="wKey" id="midG" style="left: 214px"></span>
<span class="wKey" id="midA" style="left: 255px"></span>
<span class="wKey" id="midB" style="left: 296px"></span>
<span class="wKey" id="highC" style="left:337px"></span>
<span class="bKey" id="cSharp" style="left: 72px"></span>
<span class="bKey" id="dSharp" style="left: 114px"></span>
<span class="bKey" id="fSharp" style="left: 196px"></span>
<span class="bKey" id="gSharp" style="left: 238px"></span>
<span class="bKey" id="aSharp" style="left: 280px"></span>
</div>
<!-- white key sound files -->
<audio id="c0" src="C0.mp3" preload="auto"></audio>
<audio id="d0" src="D0.mp3" preload="auto"></audio>
<audio id="e0" src="E0.mp3" preload="auto"></audio>
<audio id="f0" src="F0.mp3" preload="auto"></audio>
<audio id="g0" src="G0.mp3" preload="auto"></audio>
<audio id="a0" src="A0.mp3" preload="auto"></audio>
<audio id="b0" src="B0.mp3" preload="auto"></audio>
<!-- black key sound files -->
<audio id="cs0" src="Cs0.mp3" preload="auto"> </audio>
<audio id="ds0" src="Ds0.mp3" preload="auto"> </audio>
<audio id="fs0" src="Fs0.mp3" preload="auto"> </audio>
<audio id="gs0" src="Gs0.mp3" preload="auto"> </audio>
<audio id="as0" src="As0.mp3" preload="auto"> </audio>
</body>
</html>
2. Test the program. Press C, D, E, F, G, A, and B to play sounds. Due to the quality of sound files, please hold
each key for at least one second. If you have better sound files, please feel free to use them.
7. Capture a screen shot similar to the above one and then paste it to a Micrsoft Word document named lab10.doc
(or .docx).
Submittal
1. Upon completing all the learning activities, compress the following files to a zipped file named “lab10.zip”:
Lab10_1.htm
Lab10_2.htm
Lab10_3.htm
Lab10_4.htm
Lab10_5.htm
Lab10.doc (or .docx)
2. Upload the lab10.zip file.
Penn P. Wu, PhD
300
Programming Exercise #10:
1. Use Notepad to create a new text file named “ex10.htm” with the following lines. Be sure to replace
YourFullName with your actual full name.
<!--
Filename: ex10.htm
Student: YourFullName
-->
2. Next to the above code, create a button that says “Play 5 seconds”. Then, use the <audio> element, play(),
pause(), and currentTime to load the “bgsound1.mp3” (you had downloaded) sound file if the button is clicked.
Continously play the sound file for 5 seconds and then terminate the sound.
3. Download the “programming exercise template”, and rename it to ex10.doc. Capture a screen short similar to
the above and paste it to a Word document named “ex10.doc” (or .docx).
4. Compress both “ex10.htm” and “ex10.doc” (or .docx) file to a zip file named “ex10.zip”.
5. Submit only the .zip file.
Grading Critiera
Your code must meet all the requirements to receive full credits. No partial credit is given.
You will receive zero point if any of the required file is missing or not submitted.