With a game engine
By default a player makes its own audio context and plays straight to the speakers. In a game, give it the engine's context and a node to play into, so the music follows the game's volume, mute and pause.
ts
new Player({ context, destination });| Option | Meaning |
|---|---|
context | An AudioContext to share. Default: a new one. |
destination | Any AudioNode to play into: a music bus, a gain node. Default: the context's speakers. |
debuff
ts
import { Audio } from "@debuffjp/audio";
import { Player } from "plonkjs";
const audio = new Audio();
const music = new Player({ context: audio.ctx, destination: audio.bus("music") });
audio.volume("music", 0.7); // the music bus
audio.volume("master", muted ? 0 : 1); // mute covers music and sound effectsPhaser
ts
const sound = this.sound as Phaser.Sound.WebAudioSoundManager;
const music = new Player({ context: sound.context, destination: sound.destination });Anything else
Pass whichever AudioContext the engine uses, and a gain node of your own to control the volume:
ts
const context = new AudioContext();
const musicVolume = context.createGain();
musicVolume.connect(context.destination);
const music = new Player({ context, destination: musicVolume });
musicVolume.gain.value = 0.5;Pausing
When the game pauses, stop the music or suspend the context, depending on whether the music should keep going on the pause screen:
ts
player.stop(0.3); // fade out; play() starts again from the top
await context.suspend(); // or freeze everything, sound effects included, and resume() later