core-egret.SoundChannel

egret.SoundChannel 使用範例


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 放到資源庫

        // 取得已加載聲音資源播放, 可以用 RES.getRes, 因為在 RES.loadGroup('preload', 0, loadingView) 時音樂加載了
        const sound = RES.getRes('sound_mp3') as egret.Sound;
        let channel: egret.SoundChannel;
        // 還沒播放音樂時音樂在 0 秒處
        let soundPosition: number = 0;

        // 播放設置
        const btn = new eui.Button;
        btn.label = '播放音樂';
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            if(channel) return; // 閉免重複播放
            channel = sound.play(soundPosition, 1);
        }, this);
        this.addChild(btn);

        // 暫停設置
        const btn2 = new eui.Button;
        btn2.x = 120;
        btn2.label = '暫停音樂';
        btn2.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            if (channel) {
                soundPosition = channel.position;
                channel.stop();
                channel = null;
            }
        }, this);
        this.addChild(btn2);

    }

}

spacer

沒有留言:

張貼留言