How to preload a music

Hi everybody
I am trying to use preload function as described here. But I get this error:

Uncaught TypeError: callback is not a function

And this is my code:

cc.audioEngine.preload(this.music);
cc.audioEngine.playMusic(this.music, true, backgroundMusicVolume);

and music is a property of my mainGame class:

music: {
            default: null,
            url: cc.AudioClip,
        },

Hi,

see the following from the cocos2d\audio\CCAudioEngine.js file:

preload: function (filePath, callback)

If you use a callback function, it will work fine:

cc.audioEngine.preload(this.music, this.onPreloadFinished);

Best regards,
Zsolt

2 Likes

I use

sound: {default: null, url: cc.AudioClip}

–

if (!cc.loader.getItem(this.sound)) {
            cc.audioEngine.preload(this.sound, function () {
            });
        }
--
var id = cc.audioEngine.play(this.sound);
cc.audioEngine.setFinishCallback(id, this._onAudioEnd.bind(this));

Thank you very much for your answers.
I dont know if this is the right topic to ask this question but I am confused about the difference between cc.AudioSource and cc.AudioEngine. In this page it is written that:

Audio needs a full url, Different from res path. So we recommend avoiding url, try to use audioClip as much as possible to replace url.

But I still don’t understand it.

They mean if you use url instead of binding an audio clip to your component, you would need to do this to obtain the raw url:

cc.audioEngine.preload(cc.url.raw('resources/audio/my_clip.mp3'), callback);

Notice the code above is converting “res path” into raw url.

To answer your question on the difference between cc.AudioSource and cc.AudioEngine:

cc.AudioSource is component based, where by you have to place in on a node to use it. The scope which it can manage is limited to itself.

cc.AudioEngine is a static instance, something like a singleton which you may use it to manage all your audio instances at once. Being a singleton, you have api like pauseAll and resumeAll.

2 Likes