Add audio tag to your html page,
.....
<body onLoad="init();">
<canvas id="canvas" width="600" height="400" style="background-color:#333333;" ></canvas>
<audio id="audio" src="media/misc003.mp3">
</audio>
</body>
.....
<body onLoad="init();">
<canvas id="canvas" width="600" height="400" style="background-color:#333333;" ></canvas>
<audio id="audio" src="media/misc003.mp3">
</audio>
</body>
.....
Initializing the audio object in the js file
initWorld.js
audio = document.getElementById("audio");
Event handling for the audio object can be added as follows
audio.addEventListener("playing", start, false);
audio.addEventListener("pause", stop, false);
audio.addEventListener("ended", stop, false);
function start() {
}
function stop() {
}
audio.addEventListener("pause", stop, false);
audio.addEventListener("ended", stop, false);
function start() {
}
function stop() {
}
playing sound in the Detect collision loop
....
if((body1.GetUserData().name == "Bat" && body2.GetUserData().name == "Ball") ||(body1.GetUserData().name == "Ball" && body2.GetUserData().name == "Bat")){
audio.play();
...
}
....
if((body1.GetUserData().name == "Bat" && body2.GetUserData().name == "Ball") ||(body1.GetUserData().name == "Ball" && body2.GetUserData().name == "Bat")){
audio.play();
...
}
....
other methods that used for audio manipulation within js
Alternative, to play audio from JavaScript you can simply do this:
var audio = new Audio("song.mp3");
audio.play();
To pause
audioElement.pause();
Volume Controller
audioElement.volume=0
Play at exactly 20 seconds in the song
audioElement.currentTime=35;
audioElement.play();
var audio = new Audio("song.mp3");
audio.play();
To pause
audioElement.pause();
Volume Controller
audioElement.volume=0
Play at exactly 20 seconds in the song
audioElement.currentTime=35;
audioElement.play();
Tad dam we are done, this plays the audio file everytime there is a collision between the bat and the ball.
Reference
HTML5 Audio Tag
https://developer.mozilla.org/en/Using_audio_and_video_in_Firefox
http://www.webkit.org/blog/140/html5-media-support/
HTML5 Supported Audio Formats
No comments:
Post a Comment