Audio e Musica
Sistema Audio
Phaser supporta Web Audio API con fallback su HTML5 Audio, gestendo automaticamente la compatibilità browser.
Caricare Audio
preload() {
// Singolo file
this.load.audio('jump', 'assets/jump.mp3');
// Multiple formati (fallback browser)
this.load.audio('music', [
'assets/music.mp3',
'assets/music.ogg'
]);
// Audio sprite (multiple suoni in un file)
this.load.audioSprite('sfx', 'assets/sfx.json', [
'assets/sfx.mp3',
'assets/sfx.ogg'
]);
}
Riprodurre Suoni
create() {
// Crea sound
this.jumpSound = this.sound.add('jump');
// Play
this.jumpSound.play();
// Play con opzioni
this.jumpSound.play({
volume: 0.5,
loop: false,
delay: 0
});
// One-liner
this.sound.play('jump');
}
Musica di Sottofondo
create() {
this.music = this.sound.add('music', {
volume: 0.3,
loop: true
});
this.music.play();
}
Controllo Audio
// Play/Pause/Stop
sound.play();
sound.pause();
sound.resume();
sound.stop();
// Volume (0-1)
sound.setVolume(0.5);
// Mute
sound.setMute(true);
// Loop
sound.setLoop(true);
// Rate (velocità)
sound.setRate(1.5); // 1.5x velocità
// Seek (posizione)
sound.setSeek(10); // Vai a 10 secondi
// Detune (pitch)
sound.setDetune(100); // +100 cents
Eventi Audio
const sound = this.sound.add('music');
sound.on('play', () => console.log('Started'));
sound.on('pause', () => console.log('Paused'));
sound.on('resume', () => console.log('Resumed'));
sound.on('stop', () => console.log('Stopped'));
sound.on('complete', () => console.log('Finished'));
sound.on('looped', () => console.log('Looped'));
Audio Sprites
Combina multiple suoni in un file per ridurre richieste HTTP:
// sfx.json
{
"resources": ["sfx.mp3", "sfx.ogg"],
"spritemap": {
"jump": { "start": 0, "end": 0.5 },
"coin": { "start": 1, "end": 1.3 },
"hit": { "start": 2, "end": 2.5 }
}
}
// Usa audio sprite
preload() {
this.load.audioSprite('sfx', 'assets/sfx.json');
}
create() {
this.sfx = this.sound.addAudioSprite('sfx');
// Play specifico suono
this.sfx.play('jump');
this.sfx.play('coin');
}
Sound Manager
Gestione globale audio:
// Volume globale
this.sound.volume = 0.5;
// Mute globale
this.sound.mute = true;
// Pausa tutti i suoni
this.sound.pauseAll();
this.sound.resumeAll();
// Stop tutti i suoni
this.sound.stopAll();
// Rimuovi tutti i suoni
this.sound.removeAll();
Esempi Pratici
Effetti Sonori
create() {
this.jumpSound = this.sound.add('jump');
this.coinSound = this.sound.add('coin');
this.hitSound = this.sound.add('hit');
}
update() {
if (this.cursors.up.isDown && this.player.body.touching.down) {
this.player.setVelocityY(-330);
this.jumpSound.play();
}
}
collectCoin(player, coin) {
coin.destroy();
this.coinSound.play();
this.score += 10;
}
hitEnemy(player, enemy) {
this.hitSound.play({ volume: 0.7 });
player.health -= 10;
}
Musica Dinamica
create() {
this.menuMusic = this.sound.add('menu_music', { loop: true });
this.gameMusic = this.sound.add('game_music', { loop: true });
this.bossMusic = this.sound.add('boss_music', { loop: true });
}
startGame() {
this.menuMusic.stop();
this.gameMusic.play();
}
startBossFight() {
// Crossfade
this.tweens.add({
targets: this.gameMusic,
volume: 0,
duration: 1000,
onComplete: () => {
this.gameMusic.stop();
this.bossMusic.play();
this.tweens.add({
targets: this.bossMusic,
volume: 1,
duration: 1000
});
}
});
}
Footsteps
create() {
this.footsteps = this.sound.add('footsteps', { volume: 0.3 });
this.isWalking = false;
}
update() {
const isMoving = this.player.body.velocity.x !== 0;
if (isMoving && !this.isWalking) {
this.footsteps.play({ loop: true });
this.isWalking = true;
} else if (!isMoving && this.isWalking) {
this.footsteps.stop();
this.isWalking = false;
}
}
Suono 3D (Panning)
update() {
// Pan basato su posizione
const distance = this.player.x - this.enemy.x;
const maxDistance = 400;
const pan = Phaser.Math.Clamp(distance / maxDistance, -1, 1);
this.enemySound.setPan(pan);
// Volume basato su distanza
const volume = 1 - Math.abs(distance) / maxDistance;
this.enemySound.setVolume(volume);
}
Mute/Unmute Toggle
create() {
this.isMuted = false;
const muteButton = this.add.text(750, 10, '🔊', {
fontSize: '32px'
}).setInteractive();
muteButton.on('pointerdown', () => {
this.isMuted = !this.isMuted;
this.sound.mute = this.isMuted;
muteButton.setText(this.isMuted ? '🔇' : '🔊');
});
}
Unlock Audio (Mobile)
Su mobile, l’audio richiede interazione utente:
create() {
// Controlla se audio è bloccato
if (!this.sound.locked) {
this.startMusic();
} else {
this.sound.once('unlocked', () => {
this.startMusic();
});
// Mostra messaggio
const text = this.add.text(400, 300, 'Tap to start', {
fontSize: '32px'
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
text.destroy();
});
}
}
startMusic() {
this.music = this.sound.add('music', { loop: true });
this.music.play();
}
Preload Progress
preload() {
this.load.audio('music', 'assets/music.mp3');
this.load.on('progress', (value) => {
console.log('Loading: ' + Math.floor(value * 100) + '%');
});
this.load.on('complete', () => {
console.log('All audio loaded!');
});
}
Best Practices
- Formati multipli: Usa MP3 + OGG per compatibilità
- Audio sprites: Riduci richieste HTTP
- Volume appropriato: Musica ~0.3, SFX ~0.5-0.7
- Unlock su mobile: Gestisci audio lock
- Cleanup: Rimuovi suoni non usati
- Compressione: Usa bitrate appropriato (128kbps per musica, 64kbps per SFX)
Formati Consigliati
- MP3: Compatibilità universale
- OGG: Migliore qualità a parità di dimensione
- M4A/AAC: iOS/Safari
Conclusione
Il sistema audio di Phaser è completo e facile da usare. Audio ben implementato migliora drasticamente l’esperienza di gioco.
