The AudioSource component allows you to play sounds on any object. This system uses WebAudio and preloads all sounds when the scene loads, enabling instant playback even on mobile devices or iPad.
{
"type": "AudioSource",
"clip": "explosion.mp3",
"volume": 0.8,
"loop": false,
"playOnStart": false
}
The engine preloads ALL audio files before the game starts:
AudioSystem.loadSound()This guarantees excellent performance even on iPad and mobile devices.
PlayAudioSource(obj);
StopAudioSource(obj);
FadeOutAudio(obj, 2); // 2 seconds
FadeInAudio(obj, 2); // 2 seconds
const audio = getComponent(obj, "AudioSource");
audio.clip = "jump.mp3";
PlayAudioSource(obj);
// AUDIO_CONTROL.js
function Start(obj) {
Timer(3, "Stop_music", false, obj);
}
function Stop_music(obj) {
const audio = getComponent(obj, "AudioSource");
// Change clip
audio.clip = "jump.mp3";
// Fade in the new sound
FadeInAudio(obj, 2);
}
function Update(obj, dt) {}
Smooth transition between two music tracks.
function CrossFade(obj, newClip, time) {
FadeOutAudio(obj, time);
Timer(time, "StartNewMusic", false, { obj, newClip, time });
}
function StartNewMusic(ctx) {
const audio = getComponent(ctx.obj, "AudioSource");
audio.clip = ctx.newClip;
FadeInAudio(ctx.obj, ctx.time);
}
// Usage:
CrossFade(obj, "boss_theme.mp3", 2);
const audio = getComponent(obj, "AudioSource");
audio.volume = 0.3; // 30%
You can use PlaySound() to play sounds without an AudioSource:
PlaySound("laser.mp3", 1.0);
Useful for:
.clip to reuse the same AudioSource.