[SOLVED] Can't load sound clip from assets

Error loading audio url: : 400

How to load sound from assets? What is wrong in the code?

    this.sound = this.entity.sound;
    const soundName = 'MagicAttack';
    const clipName = soundName + '.wav';
    const url = '../assets/LoadSoundAsset/Sounds/' + clipName;
    this.app.assets.loadFromUrl(url, 'audio', function (err, asset) {
        if (!err) {
            this.sound.addSlot('Attack', {
                asset: asset
            });
        } else {
            console.error(`Error load asset '${url}'`);
        }
    }, this);

https://playcanvas.com/editor/scene/1501464

The folder structure in PlayCanvas is virtual so the URL you’ve used is not valid.

The recommended way to do this is to load the audio asset as it’s already created in the Editor: https://playcanvas.com/editor/scene/1501823

var RuntimeSoundLoad = pc.createScript('runtimeSoundLoad');

RuntimeSoundLoad.prototype.initialize = function () {
    this.sound = this.entity.sound;
    const soundName = 'MagicAttack.wav';
    const asset = this.app.assets.find(soundName, 'audio');
    asset.ready((asset) => {
        this.sound.addSlot('Attack', {
            asset: asset
        });

        const slot = this.sound.slot('Attack');
        if (slot) {
            slot.play();
        }
    });

    this.app.assets.load(asset);
};
1 Like

I think this is also a good way. Thank you.