Alza il volume. Non si sente un "dunk" quando la piazza rossa incontra un ostacolo?
Come aggiungere suoni?
Utilizzare l'HTML5 <audio> elemento per aggiungere il suono e la musica per i tuoi giochi.
Nei nostri esempi, creiamo un nuovo costruttore dell'oggetto da maneggiare oggetti sonori:
Esempio
function sound(src) {
this.sound =
document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play =
function(){
this.sound.play();
}
this.stop =
function(){
this.sound.pause();
}
}
Per creare un nuovo oggetto sonoro utilizzare il sound
del costruttore, e quando il quadrato rosso incontra un ostacolo, riprodurre il suono:
Esempio
var myGamePiece;
var myObstacles = [];
var
mySound;
function startGame() {
myGamePiece = new component(30, 30, "red" , 10, 120);
mySound = new sound("bounce.mp3");
myGameArea.start();
}
function updateGameArea() {
var x,
height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i <
myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
mySound.play();
myGameArea.stop();
return;
}
}
...
}
Prova tu stesso " Musica di sottofondo
Per aggiungere un sottofondo musicale al vostro gioco, aggiungere un nuovo oggetto Sound, e iniziare a giocare quando si avvia il gioco:
Esempio
var myGamePiece;
var myObstacles = [];
var mySound;
var
myMusic;
function startGame() {
myGamePiece = new component(30, 30, "red" , 10, 120);
mySound = new sound("bounce.mp3");
myMusic =
new sound("gametheme.mp3");
myMusic.play();
myGameArea.start();
}
Prova tu stesso "