Last active
January 3, 2023 09:04
-
-
Save sdkfz181tiger/ec9cfdcadeaf787e98256c095b9dc464 to your computer and use it in GitHub Desktop.
windowの"focus/blur"を利用した音声ファイルの再生/停止
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//========== | |
// Howler.jsを利用 | |
// https://howlerjs.com/ | |
const myHowl = new MyHowler(); | |
window.addEventListener("focus", e=>{ | |
console.log("focus"); | |
if(myHowl) myHowl.resumeBGM(); | |
}); | |
window.addEventListener("blur", e=>{ | |
console.log("blur"); | |
if(myHowl) myHowl.pauseBGM(); | |
}); | |
class MyHowler{ | |
constructor(){ | |
this._se = {}; | |
this._bgm = {}; | |
this._soundFlg = JSON.parse(localStorage.getItem("sound")); | |
if(this._soundFlg == null) this._soundFlg = true; | |
} | |
playSE(src, volume=1.0, loop=false){ | |
//this.stopSE();// Stop all SE | |
if(!this.isActive()) return; | |
if(src in this._se){ | |
this._se[src].play(); | |
return; | |
} | |
const sound = new Howl({ | |
src: src, | |
volume: volume, | |
loop: loop | |
}); | |
this._se[src] = sound; | |
this._se[src].play(); | |
} | |
stopSE(){ | |
console.log("stopSE"); | |
//if(!this.isActive()) return; | |
for(let key in this._se){ | |
if(this._se[key].seek() <= 0) continue; | |
this._se[key].stop(); | |
} | |
} | |
playBGM(src, volume=1.0, loop=false){ | |
this.stopBGM();// Stop all BGM | |
if(!this.isActive()) return; | |
if(src in this._bgm){ | |
this._bgm[src].play(); | |
return; | |
} | |
const sound = new Howl({ | |
src: src, | |
volume: volume, | |
loop: loop | |
}); | |
this._bgm[src] = sound; | |
this._bgm[src].play(); | |
} | |
stopBGM(){ | |
console.log("stopBGM"); | |
//if(!this.isActive()) return; | |
for(let key in this._bgm){ | |
if(this._bgm[key].seek() <= 0) continue; | |
this._bgm[key].stop(); | |
} | |
} | |
pauseBGM(){ | |
console.log("pauseBGM"); | |
//if(!this.isActive()) return; | |
for(let key in this._bgm){ | |
if(!this._bgm[key].playing()) continue; | |
this._bgm[key].pause(); | |
} | |
} | |
resumeBGM(){ | |
console.log("resumeBGM"); | |
if(!this.isActive()) return; | |
for(let key in this._bgm){ | |
if(this._bgm[key].seek() <= 0) continue; | |
this._bgm[key].play(); | |
} | |
} | |
isActive(){ | |
return this._soundFlg; | |
} | |
toggleActive(){ | |
this._soundFlg = !this._soundFlg; | |
if(!this._soundFlg){ | |
this.stopSE(); | |
this.pauseBGM(); | |
}else{ | |
this.resumeBGM(); | |
} | |
localStorage.setItem("sound", this._soundFlg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment