О чем этот пример
Звук — важный компонент игровой атмосферы. Phaser предоставляет мощную, но простую в использовании систему аудио, которая позволяет управлять воспроизведением, громкостью, тональностью и событиями. Эта статья разбирает официальный пример, демонстрирующий полный цикл управления звуком: от запуска и паузы отдельных треков до работы с глобальными настройками и аудиоспрайтами. Вы научитесь реагировать на события звука, создавать плавные переходы и управлять несколькими звуками одновременно, что необходимо для создания динамичного игрового саундтрека и эффектов.
Версия Phaser: код и демо в этой статье рассчитаны на Phaser 3.90.0.
Живой запуск
Ниже встроен рабочий билд примера. Оригинальный источник: GitHub.
Исходный код
class Example extends Phaser.Scene
{
tests = [
function (fn)
{
this.first.once('play', function (sound)
{
this.text.setText('Playing');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.play();
},
function (fn)
{
this.first.once('pause', function (sound)
{
this.text.setText('Paused');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.first.pause();
},
function (fn)
{
this.first.once('resume', function (sound)
{
this.text.setText('Resuming');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.resume();
},
function (fn)
{
this.first.once('stop', function (sound)
{
this.text.setText('Stopped');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.first.stop();
},
function (fn)
{
this.first.once('play', function (sound)
{
this.text.setText('Play from start');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.play();
},
function (fn)
{
this.first.once('rate', function (sound, value)
{
this.text.setText('Speed up rate');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.rate = 1.5;
},
function (fn)
{
this.first.once('detune', function (sound, value)
{
this.text.setText('Speed up detune');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.detune = 600;
},
function (fn)
{
this.first.once('rate', function (sound, value)
{
this.text.setText('Slow down rate');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.rate = 1;
},
function (fn)
{
this.first.once('detune', function (sound, value)
{
this.text.setText('Slow down detune');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.detune = 0;
},
function (fn)
{
this.tweens.add({
onStart: function ()
{
this.text.setText('Fade out');
},
targets: this.first,
volume: 0,
ease: 'Linear',
duration: 2000,
onComplete: fn
});
},
function (fn)
{
this.tweens.add({
onStart: function ()
{
this.text.setText('Fade in');
},
targets: this.first,
volume: 1,
ease: 'Linear',
duration: 2000,
onComplete: fn
});
},
function (fn)
{
this.first.once('mute', function ()
{
this.text.setText('Mute');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.first.mute = true;
},
function (fn)
{
this.first.once('mute', function ()
{
this.text.setText('Unmute');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.mute = false;
},
function (fn)
{
this.first.once('volume', function ()
{
this.text.setText('Half volume');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.volume = 0.5;
},
function (fn)
{
this.first.once('volume', function ()
{
this.text.setText('Full volume');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.volume = 1;
},
function (fn)
{
this.first.once('seek', function ()
{
this.text.setText('Seek to start');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.first.seek = 0;
},
function (fn)
{
this.second.once('play', function ()
{
this.text.setText('Play 2nd');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.second.play();
},
function (fn)
{
this.sound.once('mute', function (soundManager, value)
{
this.text.setText('Mute global');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.sound.mute = true;
},
function (fn)
{
this.sound.once('mute', function (soundManager, value)
{
this.text.setText('Unmute global');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.sound.mute = false;
},
function (fn)
{
this.sound.once('volume', function (soundManager, value)
{
this.text.setText('Half volume global');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.sound.volume = 0.5;
},
function (fn)
{
this.tweens.add({
onStart: function ()
{
this.text.setText('Fade out global');
},
targets: this.sound,
volume: 0,
ease: 'Linear',
duration: 2000,
onComplete: fn
});
},
function (fn)
{
this.tweens.add({
onStart: function ()
{
this.text.setText('Fade in global');
},
targets: this.sound,
volume: 1,
ease: 'Linear',
duration: 2000,
onComplete: fn
});
},
function (fn)
{
this.sound.once('pauseall', function (soundManager)
{
this.text.setText('Pause all');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.sound.pauseAll();
},
function (fn)
{
this.sound.once('resumeall', function (soundManager)
{
this.text.setText('Resume all');
this.time.addEvent({
delay: 2000,
callback: fn,
callbackScope: this
});
}, this);
this.sound.resumeAll();
},
function (fn)
{
this.sound.once('stopall', function (soundManager)
{
this.text.setText('Stop all');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.sound.stopAll();
},
function (fn)
{
this.audioSprite.once('play', function (sound)
{
this.text.setText('Play sprite');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.audioSprite.play('07');
},
function (fn)
{
this.audioSprite.once('pause', function (sound)
{
this.text.setText('Pause sprite');
this.time.addEvent({
delay: 1000,
callback: fn,
callbackScope: this
});
}, this);
this.audioSprite.pause();
},
function (fn)
{
this.audioSprite.once('resume', function (sound)
{
this.text.setText('Resume sprite');
this.time.addEvent({
delay: 1500,
callback: fn,
callbackScope: this
});
}, this);
this.audioSprite.resume();
},
function (fn)
{
this.audioSprite.once('play', function (sound)
{
this.text.setText('Multiple sprites');
this.time.addEvent({
delay: 10000,
callback: fn,
callbackScope: this
});
}, this);
const sounds = [ '01', '02', '03', '03', '05' ];
for (let i = 0; i < sounds.length; i++)
{
this.time.addEvent({
delay: i * 2000,
callback: this.audioSprite.play.bind(this.audioSprite, sounds[i]),
callbackScope: this.audioSprite
});
}
},
function (fn)
{
this.audioSprite.once('play', function (sound)
{
this.text.setText('Loop sprite');
this.time.addEvent({
delay: 4000,
callback: fn,
callbackScope: this
});
}, this);
this.audioSprite.play('06', {
loop: true
});
},
function (fn)
{
this.tweens.add({
onStart: function ()
{
this.text.setText('Fade out sprite');
},
targets: this.audioSprite,
volume: 0,
ease: 'Linear',
duration: 4000,
onComplete: function ()
{
this.audioSprite.volume = 1;
this.audioSprite.stop();
fn();
}
});
}
];
audioSprite;
second;
first;
text;
preload ()
{
this.load.setBaseURL('https://raw.githubusercontent.com/phaserjs/examples/master/public/');
const head = document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://fonts.googleapis.com/css?family=Sorts+Mill+Goudy';
head.appendChild(link);
this.load.image('prometheus', 'assets/pics/Prometheus Brings Fire To Mankind.jpg');
this.load.audio('overture', [
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/Overture.ogg',
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/Overture.mp3'
]);
this.load.audioSprite('creatures', 'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.json', [
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.ogg',
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.mp3'
]);
}
create ()
{
this.sound.pauseOnBlur = false;
const prometheus = this.add.image(400, 300, 'prometheus');
prometheus.setScale(600 / prometheus.height);
this.text = this.add.text(400, 300, 'Loading...', {
fontFamily: '\'Sorts Mill Goudy\', serif',
fontSize: 80,
color: '#fff',
align: 'center'
});
this.text.setOrigin(0.5);
this.text.setShadow(0, 1, '#888', 2);
this.first = this.sound.add('overture', { loop: true });
this.second = this.sound.add('overture', { loop: true });
this.audioSprite = this.sound.addAudioSprite('creatures');
this.enableInput.call(this);
}
chain (i)
{
return () =>
{
if (this.tests[i])
{
this.tests[i].call(this, this.chain.call(this, ++i));
}
else
{
this.text.setText('Complete!');
this.time.addEvent({
delay: 5000,
callback: this.enableInput,
callbackScope: this
});
}
};
}
enableInput ()
{
this.text.setText('Click to start');
this.input.once('pointerdown', function (pointer)
{
this.tests[0].call(this, this.chain.call(this, 1));
}, this);
}
}
/**
* @author Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
*
* Prometheus Brings Fire To Mankind - Painting by Heinrich Füger, 1817, Public Domain
* The Creatures of Prometheus, Op. 43, Overture - Music by Ludwig van Beethoven, 1801, Public Domain
*/
const config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600,
scene: Example,
audio: {
noAudio: true
}
};
const game = new Phaser.Game(config);
Инициализация и загрузка аудио
Перед использованием звука его необходимо загрузить. В методе preload() примера используется this.load.audio() для загрузки обычного звукового файла и this.load.audioSprite() для загрузки аудиоспрайта — специального файла, содержащего несколько звуковых фрагментов (спрайтов) с метаданными.
this.load.audio('overture', [
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/Overture.ogg',
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/Overture.mp3'
]);
this.load.audioSprite('creatures', 'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.json', [
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.ogg',
'assets/audio/Ludwig van Beethoven - The Creatures of Prometheus, Op. 43/sprites.mp3'
]);
После загрузки в create() звуки создаются как объекты, которыми можно управлять. Обратите внимание на опцию loop: true для фоновой музыки и отключение автоматической паузы при потере фокуса окна браузера через this.sound.pauseOnBlur = false.
this.first = this.sound.add('overture', { loop: true });
this.second = this.sound.add('overture', { loop: true });
this.audioSprite = this.sound.addAudioSprite('creatures');
Базовое управление воспроизведением и события
Основные методы управления звуком — play(), pause(), resume() и stop(). Phaser позволяет отслеживать момент их срабатывания через события. В примере для этого используется метод .once(), который подписывает обработчик на одно срабатывание события.
this.first.once('play', function (sound) {
this.text.setText('Playing');
// ... Действия после начала воспроизведения
}, this);
this.first.play();
Аналогично работают события pause, resume и stop. Это позволяет синхронизировать игровые процессы (например, обновление интерфейса или запуск анимации) с состоянием аудио. Важно передавать контекст (this) в обработчик, чтобы иметь доступ к полям сцены.
Изменение свойств звука: громкость, скорость, тон
Свойства звукового объекта можно менять напрямую, и эти изменения также генерируют события. Например, изменение скорости воспроизведения (rate) или тона (detune).
this.first.once('rate', function (sound, value) {
this.text.setText('Speed up rate');
}, this);
this.first.rate = 1.5;
Громкостью можно управлять как напрямую, присваивая значение свойству volume, так и плавно, с помощью твинов. В примере используется система анимаций Phaser (this.tweens.add()) для создания эффектов затухания (fade in/out).
this.tweens.add({
targets: this.first,
volume: 0,
ease: 'Linear',
duration: 2000,
onComplete: fn
});
Свойства mute и volume также есть у глобального менеджера звуков this.sound, что позволяет управлять всем звуком в игре разом.
Глобальное управление звуком
Объект this.sound (менеджер звуков) управляет всеми звуками в игре. С его помощью можно приостановить, возобновить или остановить воспроизведение всех звуков одновременно, а также изменить общую громкость или включить/выключить звук.
// Приостановить все звуки
this.sound.pauseAll();
// Возобновить все звуки
this.sound.resumeAll();
// Остановить все звуки
this.sound.stopAll();
// Изменить глобальную громкость
this.sound.volume = 0.5;
С менеджером также связаны события mute, volume, pauseall, resumeall, stopall. Их можно слушать, чтобы реагировать на глобальные изменения аудио в игре.
Работа с аудиоспрайтами
Аудиоспрайты — это мощный инструмент для работы с короткими звуковыми эффектами, упакованными в один файл. После загрузки спрайта (creatures) можно проигрывать отдельные его фрагменты по ключу.
// Проиграть фрагмент с ключом '07'
this.audioSprite.play('07');
С аудиоспрайтом можно работать так же, как с обычным звуком: ставить на паузу, менять громкость, отслеживать события play. Кроме того, методы управления поддерживают дополнительные опции, например, зацикливание конкретного фрагмента.
this.audioSprite.play('06', {
loop: true
});
В примере показано, как организовать последовательное воспроизведение нескольких фрагментов с задержкой, используя this.time.addEvent().
Организация последовательности действий
Весь пример построен как демонстрация: последовательный вызов тестов из массива tests. Ключевую роль играет функция chain(), которая обеспечивает выполнение тестов один за другим.
chain (i) {
return () => {
if (this.tests[i]) {
// Вызываем текущий тест, передав ему функцию,
// которая запустит следующий тест (chain(i+1))
this.tests[i].call(this, this.chain.call(this, ++i));
}
};
}
Каждая функция-тест принимает колбэк (fn), который должен быть вызван по завершении своего действия (часто по срабатыванию события или окончанию твина). Этот подход позволяет создавать сложные, управляемые по времени аудио-сценарии, что полезно для интро, кат-сцен или туториалов.
Что попробовать дальше
Система аудио Phaser — это гибкий инструмент, покрывающий все базовые потребности игры: от простого воспроизведения до тонкой настройки параметров и работы с событиями. Экспериментируйте: создайте систему случайного выбора фоновых треков, реализуйте динамическое изменение громкости в зависимости от игровой ситуации (например, приглушите музыку в диалогах) или используйте аудиоспрайты для озвучки интерфейса с минимальными затратами ресурсов.
