Start sound after completely loaded

I have a scene that, after loading, should start with a cutscene. I made the entire dialogue in a single audio file that auto plays.
You’re supposed to get to the scene via a button.

The problem now is that, when I switch the scene, the sound already starts to play just before the scene with the cutscene is actually visible and starts to play. That causes a delay between audio and the cutscene.

The code for switching the scene with the button:

var StartButton = pc.createScript('startButton');

StartButton.attributes.add("sceneName", {
    type: "string",
    default: "",
    title: "Name of the scene to be loaded"
});

StartButton.attributes.add("rootEntity", {
    type: "entity",
    default: ""
});

// initialize code called once per entity
StartButton.prototype.initialize = function() {
    this.scene = this.app.scenes.find(this.sceneName);
    this.app.scenes.loadSceneData(this.scene, function(err, sceneItem) {
        if (err) {
            console.error(err);
        }
    });

    this.entity.button.on('click', function(event) {
        // Aktuelle Szenenhierarchie vom Speicher löschen
        this.rootEntity.destroy();

        //Neue Szene und dessen Einstellungen laden
        this.app.scenes.loadSceneHierarchy(this.scene.url, function (err, scene) {
        if (err){
            console.log(err);
        }
        });
        this.app.scenes.loadSceneSettings(this.scene.url, function (err, scene) {
            if (err){
                console.log(err);
            }
        });
    }, this);
};

Thank you so much in advance

As I understand this happens if you use set autoplay in the audio component slot parameters? Did you try to set it to false and manually call play function on the corresponding audio slot from a script (for example, in postInitialize)?

this.entity.sound.play('YourAudioSlotName');

Personally, I use this approach to organize different sounds assets playing using one slot (accordingly, different slots can be made for different types).

/**
 * @param {pc.Asset} soundAsset
 */
AudioManager.prototype.playSound = function(soundAsset) {
    if(!soundAsset) return; // can be removed if sure that u always pass defined soundAsset
    this.entity.sound.slots['Sound'].asset = soundAsset.id;
    soundAsset.ready(function() {
        this.entity.sound.play('Sound');
    }, this);
};

Take into account that the sound assets must be loaded (if there is Preload set to true, which is default – then you can not worry about it), otherwise ready function will do its job and, accordingly, the audio will be played with a delay.

1 Like

Hi @robert.ua ,

Yes, I have already done that approach…kinda.

I duplicated the first cut of the cutscene and let the sound play after the first one