[SOLVED] Loading Audio at run time

I am trying to load and play the audio from an url at runtime.
But i am not able to play it.

Bgmcontroller.prototype.OnEnable=function()
{
   // this.sound.sound.stop('a');
   
    if(this.sound.sound.slot("a")._asset==null)
    {
        
        var soundUrl = "https://immyar123.github.io/AnimeVerse/asuma%20sarutobi%20chakara%20blades.mp3";
        var soundAsset = new pc.Asset("MyAudioFile.mp3", "audio", { url: soundUrl }); 
        this.app.assets.add(soundAsset);

       

        soundAsset.once('load', (asset)=>
        {
            this.sound.sound.slot("a")._asset=asset;
            this.sound.sound.play('a');
            console.log(this.sound.sound.slot("a"));

        },this); 

            this.app.assets.load(soundAsset);

    }
    else
    {
        this.sound.sound.play('a');
    }

};

Hi @Ashish_Rana,

Not sure what’s wrong there, are you getting any error? You should avoid using private properties to assign the asset to the sound slot.

You can use this method to load the remote file and create the asset in one action:
https://developer.playcanvas.com/api/pc.AssetRegistry.html#loadFromUrl

From there use the public asset property to assign the asset to the slot:
https://developer.playcanvas.com/api/pc.SoundSlot.html#asset

1 Like

Thanx Leonidas,
it worked.