0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pixi-soundで音ファイルをpixi.jsでの画像ファイルと同様に扱う

Posted at

HTML5用の描画ライブラリであるpixi.jsは、音周りをサポートしていない。
他のオーディオライブラリであるhowler.jsとかを使っても良いが、pixi-soundというライブラリを使うとPIXI.Loaderを画像等と共有できるので使い勝手が良い。

公式のgithubによると、npmでのインストールが可能らしい。

Installation is available by NPM:
npm i @pixi/sound --save

もしくはここから直接pixi-sound.min.jsをダウンロードして、pixi.min.jsの後に読み込む。

index.html
<html>
<head>
  <script src="pixi.min.js"></script>
  <script src="pixi-sound.min.js"></script>
</head>

<body>
  <div id="game"></div>
  <script src="script.js"></script>
</body>
</html>

あとは、音ファイルを画像ファイルと同等に扱うことができる。
ただしindex.htmlと同一ディレクトリにpixi.min.js, pixi-sound.min.js, script.js, image.png, sound.mp3のファイルがあるとする。

script.js
//Aliases
let Application = PIXI.Application,
    loader = PIXI.loader,
    TextureCache = PIXI.TextureCache,
    resources = PIXI.loader.resources,
    Sprite = PIXI.Sprite,
    Container = PIXI.Container,
    Sound = PIXI.sound.Sound,
    id = loader.resources;

//アプリケーション宣言
const width = 500;
const height = 600;
let app= new Application({
    width:width, 
    height:height,
});

//appをdivに貼り付け
document.getElementById("game").appendChild(app.renderer.view);

//素材ファイルの読み込み
loader.add("imageName", "image.png");
loader.add("soundName", "sound.mp3");
loader.load(setup);

//スプライト
let spr;
//音オブジェクト
let snd;

function setup(){
    spr = new Sprite(id["imageName"].texture);
    app.stage.addChild(spr);//画面にスプライトを貼り付け

    snd = new Sound.from(id["soundName"].sound);
    snd.volume = 0.25;//SoundオブジェクトのプロパティもSpriteと同じように変更できる

    app.ticker.add(loop);
}

function loop(delta){
    snd.play();//毎フレーム音が鳴る(うるさい)
    spr.rotation += (0.5-Math.random())*0.01;//スプライトが動く(うざい)
}

細かい使い方等は公式の説明書きを参考に。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?