LoginSignup
1
0

More than 3 years have passed since last update.

[PlayCanvas] サウンドの再生終了したタイミングで処理を実行する

Posted at

はじめに

  • 特定のサウンドの再生が終わった後に処理を走らせたい。
  • ザックリと調べてもそういったイベントもなさそうなので、とりあえず自前でどうにかする。
  • 重要:これはベストな方法ではない。

実装

マウスをクリックしたら音声を再生、その音声終了したらコンソールにログを表示します。

Sample
var Sample= pc.createScript('sample');

// initialize code called once per entity
Sample.prototype.initialize = function() {
    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.mouseDown, this);
};

Sample.prototype.mouseDown = function(event) {
    var name = 'Sample';

    if( this.entity.sound ){
        this.entity.sound.play( name );

        if( this.entity.sound.slots[name] ){
            var id = this.entity.sound.slots[name]._asset;
            var asset = this.app.assets.get( id );
            var duration = asset._resources[0].buffer.duration;

            setTimeout(()=>{
                console.log('Played audio:', asset.name);
            }, pc.math.clamp(duration * 1000));
        }
    }
};

解説

前提として、アセットがちゃんと存在していて、Preloadにチェックが入ってるものとします。

アセットを取得する

SoundのスロットにはAsset IDが格納されています。そのIDとthis.app.assets.get()を使用してアセットを取得します。

var id = this.entity.sound.slots[name]._asset;
var asset = this.app.assets.get( id );

アセットから再生時間を取得する

取得したAssetがちゃんとAudioであるならば、_resources[0].bufferに再生時間やサンプリングレートが格納されています。今回必要なのは再生時間(duration)です。

var duration = asset._resources[0].buffer.duration;

再生終了時に処理を走らせる。

取得した再生時間をミリ秒単位に変換しsetTimeout()を使って処理を走らせます。
今回は何の音声が再生終了したのかをコンソールに吐き出します。

setTimeout(()=>{
    console.log('Played:', asset.name);
}, pc.math.clamp(duration * 1000));

おわりに

サウンドのダッキングをするために調べていた時の副産物なので、ベストな方法は他者にまかせます。

1
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
1
0