iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 17
3
Software Development

遊戲之美 - 連連看經典遊戲開發系列 第 17

[17- Pixi教學] 音樂音效設定

PixiJS Sound

PixiJS本身有開發可供使用的PIXI.sound

並且官網上有很詳細的使用範例以及API手冊:PixiJS Sound

PixiJS Sound最大的優點是它可以與pixi的素材共用同一個Loader,下載mp3的資源檔案。並支援相當多種的音樂格式,也可以將多個音效壓縮在一個mp3內,再根據要開始與結束的秒數去切成多個聲音資源。在一般的狀況下,PixiJS Sound應為搭配PixiJS首選可使用的音樂函式庫

PixiJS Sound於TypeScript

不過很可惜的,PixiJS Sound現在在typescript上的支援度尚不是那麼的好。PixiJS Sound並沒有推出針對type script專案的函式庫,在開發上會帶給使用typescript的人帶來一些困擾。因此我選擇了另一款很受歡迎的聲音函式庫howler

下面是howler.js一些簡單的使用範例

var sound = new Howl({
  src: ['sound.webm', 'sound.mp3']
});

// Clear listener after first call.
sound.once('load', function(){
  sound.play();
});

// Fires when the sound finishes playing.
sound.on('end', function(){
  console.log('Finished!');
});
var sound = new Howl({
  src: ['sound.webm', 'sound.mp3', 'sound.wav'],
  autoplay: true,
  loop: true,
  volume: 0.5,
  onend: function() {
    console.log('Finished!');
  }
});

在連連看專案內使用Howler

ResourcesList.ts裡新增要下載的mp3檔案

public static sound:Array<Resources> = [
    new Resources('Sound_bg','assets/bg.mp3'),
    new Resources('Sound_level_pass','assets/level_pass.mp3'),
    new Resources('Sound_select_1','assets/select_1.mp3'),
    new Resources('Sound_select_crrect','assets/select_crrect.mp3'),
    new Resources('Sound_select_error','assets/select_error.mp3')
];

新增SoundMgr.ts內容如下:

import {ResourcesList} from "./ResourcesList";

export class SoundMgr {
    private static soundList:Array<SoundInfo> = new Array<SoundInfo>();
    public static load(){
        ResourcesList.sound.forEach(element => {
            let info = new SoundInfo(element.id, element.path);
            this.soundList.push(info);
        });
    }
    public static play(id, loop = false){
        this.soundList.forEach(element => {
            if (element.soundID == id){
                element.sound.loop(loop);
                element.sound.play();
            } 
        });
    }
}
class SoundInfo{
    public soundID:string;
    public path:string;
    public sound:Howl;
    constructor(_id:string, url:string) {
        this.soundID = _id;
        this.path = url;
        this.load();
    }
    public load(){
        this.sound = new Howl({src: this.path});
    }
}

Main.ts加入

//播放背景音樂
SoundMgr.play('Sound_bg',true);

並呼叫load()來下載音檔

SoundMgr.load();

需要注意的是,因為howler的loader與pixi本身的是兩個不同的loader,所以像這樣的寫法,很有可能剛進遊戲音效會還沒有載入完成,等到載完後才會播放聲音。如果希望一定要剛進遊戲就有聲音,那就需要把拿掉loading page的判斷另外加上音效是否載入完成的判斷。

今日成果

專案下載:ironman20181101
線上demo:http://claire-chang.com/ironman2018/1101/


上一篇
[16- Pixi教學] 與網頁互動-控制loading page
下一篇
[18- Pixi教學] 按鈕製作
系列文
遊戲之美 - 連連看經典遊戲開發31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言