egret.Sound 使用範例
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.onPause = () => egret.ticker.pause();
egret.lifecycle.onResume = () => egret.ticker.resume();
egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
this.runGame();
}
private async loadResource() {
let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
await RES.loadConfig('resource/default.res.json', 'resource/');
await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
await RES.loadGroup('preload', 0, loadingView);
this.stage.removeChild(loadingView);
}
private async runGame() {
await this.loadResource();
// --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---
// 瀏覽器限制, 請至少點擊一次遊戲畫面往後才能播放音樂, 所以要設計按鈕
// 請先準備 sound.mp3 放到資源庫
// 方法1, 手動載入資源並播放
const sound1 = new egret.Sound;
// once 為只會執行一次的事件監聽
sound1.once(egret.Event.COMPLETE, (e: egret.Event) => (e.target as egret.Sound).play(0, 1), this);
const btn1 = new eui.Button;
btn1.label = '播放音樂1';
btn1.addEventListener(egret.TouchEvent.TOUCH_TAP, () => sound1.load('resource/assets/sound.mp3'), this);
this.addChild(btn1);
// 方法2, 取得已加載聲音資源播放, 可以用 RES.getRes, 因為在 RES.loadGroup('preload', 0, loadingView) 時音樂加載了, 所以可以不用上述方法
const sound2 = RES.getRes('sound_mp3') as egret.Sound;
const btn2 = new eui.Button;
btn2.y = 100;
btn2.label = '播放音樂2';
btn2.addEventListener(egret.TouchEvent.TOUCH_TAP, () => sound2.play(0, 1), this);
this.addChild(btn2);
}
}
沒有留言:
張貼留言