1.音频管理脚本AudioMgr.ts
exprot default class AudioMgr{
bgmVolume = 1.0
sfxVolume = 1.0
bgmAudioID = -1
init(){
let t = localStorage.getItem("bgmVolume")
if(t){
this.bgmVolume = parseFloat(t)
}else{
localStorage.setItem("bgmVolume",this.bgmVolume.toString())
}
t = localStorage.getItem("sfxVolume")
if(t){
this.sfxVolume = parseFloat(t)
}else{
localStorage.setItem("sfxVolume",this.sfxVolume.toString())
}
cc.game.on(cc.game.EVENT_HIDE,()=>{
cc.audioEngine.pauseAll()
})//切到后台停止
cc.game.on(cc.game.EVENT_SHOW,()=>{
cc.audioEngine.resumeAll()
})//回到前台播放
}
getUrl(url){
return "sound/" + url
}
playBgm(url){
let audioUrl = this.getUrl(url)
if(this.bgmAudioID >=0){
cc.audioEngine.stop(this.bgmAudioID)
}
if(this.bgmAudioID >=0){
cc.audioEngine.stop(this.bgmAudioID)
}
let clip =gameMgr.Instance.audioClip[audioUrl]
if(clip){
this.bgmAudioID = cc.audioEngine.play(clip,true,this.bgmVolume)
}else{
cc.loader.loadRes(audioUrl,cc.AudioClip,(err,clip)=>{
if(err){
console.log(err)
}else{
this.bgmAudioID = cc.audioEngine.play(clip,true,this.bgmVolume)
//true 循环播放
gameMgr.Instance.audioClip[audioUrl] = clip
}
})
}
}
playSFX(url){
let audioUrl = this.getUrl(url)
let clip =gameMgr.Instance.audioClip[audioUrl]
if(clip){
this.bgmAudioID = cc.audioEngine.play(clip,false,this.bgmVolume)
}else{
cc.loader.loadRes(audioUrl,cc.AudioClip,(err,clip)=>{
cc.audioEngine.play(clip,false,this.sfxVolume)
gameMgr.Instance.audioClip[audioUrl] = clip
})
}
}
playSFXType(url,i){
if(i == 0){
url = "local/" + url
}else{
url = "mandarin" + url
}
this.playSFX(url)
}
setBGMVolume(v){
if(this.bgmAudioID>0){
if(v > 0){
cc.audioEngine.resume(this.bgmAudioID)
}else{
cc.audioEngine.pause(this.bgmAudioID)
}
}
if(this.bgmVolume != v){
localStorage.setItem("bgmVolume",v.tostring())
this.bgmVolume = v
cc.audioEngine.setVolume(this.bgmAudio,v)
}
}
setSFXVolume(v){
if(this.sfxVolume != v){
localStorage.setItem("sfxVolume",v.tostring())
this.sfxVolume = v
}
}
pauseAll(){
cc.audioEngine.pauseAll()
}
resumeAll(){
cc.audioEngine.resumeAll()
}
}