Better sound handling

This commit is contained in:
KingOfDog 2019-04-10 17:58:02 +02:00 committed by Marcel
parent fd1e0447a4
commit 07424dd662
2 changed files with 24 additions and 5 deletions

10
main.js
View File

@ -1,9 +1,9 @@
const sounds = {
hitBlock: new Audio('assets/hit_block.wav'),
hitCoin: new Audio('assets/hit_coin.wav'),
hitBall: new Audio('assets/hit_ball.wav'),
roundOver: new Audio('assets/round_success.wav'),
gameOver: new Audio('assets/game_over.wav')
hitBlock: new SoundManager('assets/hit_block.wav'),
hitCoin: new SoundManager('assets/hit_coin.wav'),
hitBall: new SoundManager('assets/hit_ball.wav'),
roundOver: new SoundManager('assets/round_success.wav'),
gameOver: new SoundManager('assets/game_over.wav'),
};
let coinCount = 0;

19
sound-manager.js Normal file
View File

@ -0,0 +1,19 @@
class SoundManager {
constructor(soundSource) {
this.soundSource = soundSource;
this.sound = new Audio(this.soundSource);
this.lastPlayed = 0;
}
play() {
if (Date.now() - this.lastPlayed < 50)
return;
const node = this.sound.cloneNode();
node.play();
setTimeout(() => {
node.remove();
}, this.sound.duration * 1000);
this.lastPlayed = Date.now();
}
}