Appearance
AudioPlayer 音频播放
是一个用于音频播放控制的类,一个AudioPlayer为一个单独的音轨,等于提供加载、播放、暂停、停止、进度回调等功能。
枚举说明
AudioType 音频类型
音频类型,主要用于区分音乐类型,便于引擎管理
AudioType.BGM音乐AudioType.EFFECT音效AudioType.VOICE语音
使用方法
tips: 如果播放的音乐是背景音乐,且回到剧情后仍然使用这个音乐。强烈建议使用LM.playBgm方法。AudioPlayer主要为播放多个音乐。
简单使用
给音频设置播放地址,播放类型后,调用play()方法就可以直接播放。地址和类型是必须的。后续可按需求调用对应方法。
typescript
let audioPlayer = new LM.AudioPlayer();
audioPlayer.loadSource("Audio/SE/吹风.mp3")
.setType(LM.AudioType.BGM)
.play();
// 后续播放其他音乐
audioPlayer.loadSource("Audio/SE/吹风2.mp3")
audioPlayer.play();
// 后续设置音量
audioPlayer.setVolume(30)暂停播放和恢复,和日常使用的音乐播放器一样,暂停后,调用resume()方法可以恢复播放。但使用stop后,只能用play方法从头播放了。
typescript
audioPlayer.pause();
audioPlayer.resume();使用避坑
或者在scene中创建AudioPlayer实例,scene关闭时调用dispose()销毁音频实例。避免在创建AudioPlayer,跳转另一个Scene后,失去对AudioPlayer的引用,导致这个AudioPlayer失去掌控,无法操作。
错误使用,关闭scene后,我们失去对这个AudioPlayer的引用,导致这个AudioPlayer失去掌控,无法操作。
typescript
@LM.Class("AudioPlayerScene")
export class AudioPlayerScene extends LM.Scene{
init(){
let audioPlayer = new LM.AudioPlayer();
audioPlayer.loadSource("Audio/SE/吹风.mp3")
.setType(LM.AudioType.BGM)
.onLoaded(()=>{
console.log('加载完成')
})
.setVolume(30)
.setLoop(true)
.onComplete(()=>{
console.log('播放完成')
})
.onProgress((progress)=>{
console.log('播放进度',progress)
})
.play();
this.showScene("NextScene",[]);
this.close([]);
// 关闭后audioPlayer 还会继续播放,并且失去掌控,除非关闭所有scene 回到剧情时才会关闭
}
}正确使用 在Scene被销毁时将音乐对象销毁。beforeDestroy中销毁AudioPlayer
typescript
@LM.Class("AudioPlayerScene")
export class AudioPlayerScene extends LM.Scene{
private audioPlayer:LM.AudioPlayer;
beforeDestroy(){
this.audioPlayer.dispose();
}
init(){
this.audioPlayer = new LM.AudioPlayer();
this.audioPlayer.loadSource("Audio/SE/吹风.mp3")
.setType(LM.AudioType.BGM)
.onLoaded(()=>{
console.log('加载完成')
})
.setVolume(30)
.setLoop(true)
.onComplete(()=>{
console.log('播放完成')
})
.onProgress((progress)=>{
console.log('播放进度',progress)
})
.play();
}
}