Unable to load an audio asset at runtime

I am trying to load a sound from a URL at runtime (I am not able to know in advance the URL of the sound), but I cannot make it work.

This is what I do in my addSound function:

Primitives.addSound = function(app, entity, soundUrl) 
{
    entity.addComponent("sound");

    var soundAsset = new pc.Asset(soundUrl, "audio", { url: soundUrl }); 
    app.assets.load(soundAsset);

    var onAssetLoad = function() 
    {
        entity.sound.addSlot('MySoundSlot', {
            loop: true,
            autoPlay: true,
            asset: soundAsset,
        });

        entity.sound.positional = true;
    };

    soundAsset.once('load', onAssetLoad);  
}

The onLoadAsset function is called, the sound is loaded (I can see in the console the length, frequency, etc. of the audio file) but no sound is played.

However, if I use an asset that is in the project asset list, it works instead:

Primitives.addSound = function(app, entity) 
{
     entity.addComponent("sound");

     var existingAsset = app.assets.get(12887060);
        
     entity.sound.addSlot('MySoundSlot', {
          loop: true,
          autoPlay: true,
          asset: existingAsset,
     });

    entity.sound.positional = true;
}

What am I doing wrong???
Isn’t it possible to load a sound from a URL at runtime???

Looks like the missing step is to add the asset to the registry. (Also, you should call the load function after the the listener has been subscribed).

        var entity = new pc.Entity();
        this.app.root.addChild(entity);

        entity.addComponent("sound");

        var soundUrl = "https://raw.githubusercontent.com/yaustar/3dmodel-Playcanvas/master/switch3.ogg";
        var soundAsset = new pc.Asset("some name.ogg", "audio", { url: soundUrl }); 
        this.app.assets.add(soundAsset);

        var onAssetLoad = function(asset) 
        {
            entity.sound.addSlot('MySoundSlot', {
                loop: true,
                autoPlay: true,
                asset: asset
            });

            entity.sound.positional = true;
        };

        soundAsset.once('load', onAssetLoad); 
        this.app.assets.load(soundAsset);

Oh!
Thanks.

That was the problem.
I thought that the load function was responsible for adding the asset to the app asset registry…

Strangely not :thinking:

I personally use loadFromUrl which does that and simplifies the call a fair bit.

Yaustar, hello again. Can you possibly give us an example of suing loadFromUrl? I am using it for “texture” but I don’t know how exactly it should be used for audio. Thanks again.

It be almost exactly the same but changing the asset type to audio

1 Like