Using the PlayerAudio Playback

Audio

How audio works in the PanelWave Player — the WebAudio engine, its four channels, browser autoplay policy handling, volumes, and sequence tracks.

The player ships a WebAudio-based AudioEngineService for music, ambience, voice-over, and sound effects, plus a UserGestureService that deals with browser autoplay restrictions. Video sound is handled separately by the video layer (muted by default).

The shell drives the engine from the manifest on its own: a PanelAudioService starts each panel's audio when the panel becomes current and stops it when the reader leaves, and the toolbar's Audio / SFX toggles (and the settings modal's audio preferences) mute the corresponding buses. Hosts only need the API below for audio the manifest does not describe — a site-wide jingle, a reader-triggered voice sample, and so on.

What the shell plays automatically

For the current panel (after variant resolution, so a variant's audio override wins), the shell collects:

  • every entry of panels.<id>.audio[] (schema AudioTrack), and
  • every layer with kind: "audio" (schema AudioLayer; its bus comes from the catalog asset's role).

Each entry is resolved against the asset catalog (assets.catalog[assetId], category audio; the first variant the browser reports it can play, its src resolved against assets.base.audioBase / mediaBase) and started with:

Manifest fieldEffect
roleBus: ambient, music, voiceover, sfx as-is; ui plays on the sfx bus (so the SFX toggle covers it); none (the default) on the music bus (only the master Audio toggle silences it). Falls back to the catalog asset's role.
loopLoops while the panel is current.
gainPer-track gain 0–2 (a per-track gain node, so it never touches the bus level).
startAtMsDelay after panel enter; cancelled if the reader leaves first.
visibleIfJSON Logic against the variable context; re-evaluated on every variable change, so a track can start mid-panel when a condition becomes true.

Lifecycle rules:

  • Leaving a panel stops its tracks — looping ones with a short fade (PANEL_AUDIO_LEAVE_FADE_MS, 250 ms), one-shots immediately.
  • Continuity: a looping track that the next panel references too (same assetId) keeps playing uninterrupted; only its gain is updated. This is how a street ambience spans a scene.
  • One-shots restart on every panel enter that references them; a one-shot that finished releases its element on ended.
  • Autoplay policy: a track the browser refuses before the first user gesture is remembered and retried on that gesture (the AudioContext is resumed at the same time), so audio starts as early as the browser allows without any host code.
  • Same panel, variables changed: nothing restarts; only visibleIf results and gains are re-applied.
  • Locked panels stay silent (from player 1.3.0): while the current panel is locked for the reader — by a paywall rule or as an x-locked stub — its tracks don't play, so an age-gated or paid entry panel no longer plays its music behind the age gate or paywall. The audio starts once the lock lifts (age confirmed, purchase completed). The same holds while the work's cover is shown.
  • Missing or non-audio assets are skipped with a single console warning per asset.

Chapter-level sequence tracks (chapter.sequenceAudioTracks, the CMS timeline's music and ambience) are played by the shell too (from player 1.6.0) — see Sequence tracks.

Toggles and preferences

ControlEngine effect
Toolbar Audio (settings "Enable audio")setMasterMuted(!enabled) — every bus; video layers follow masterMuted$ and stay muted too.
Toolbar SFX (settings "Enable sound effects")setRoleMuted('sfx', !enabled)
Toolbar Speech (settings "Show speech bubbles")hides the balloons only (until player 1.11 it also muted voiceover)
Toolbar Voices (settings "Hear character voices", player 1.12)setRoleMuted('voiceover', !enabled) and BubbleVoiceService.setEnabled(enabled) — the spoken lines stop or start
Stored masterVolume / sfxVolume preferencessetMasterVolume / setRoleVolume('sfx', …) — applied independently of the mute flags.

Initial state follows the reader's explicitly set preference when there is one (persisted in localStorage as pw-preferences, see PlayerStateService), else the work's settings.ui.audioDefault / sfxDefault / speechDefault / voicesDefault. See Toolbar controls.

Channels (buses)

The engine mixes every track through a per-role gain node into a master gain:

track → role gain (ambient | music | voiceover | sfx) → master gain → output

The four roles match the manifest's audio roles (see Audio in the schema):

RoleTypical use
ambientBackground atmosphere (rain, crowd noise)
musicScore / theme music
voiceoverNarration, character voice
sfxShort effects (door slam, whoosh)

From player 1.10.0, an audio player widget or a video window ducks the music and ambient buses to 20 % while it plays (duckMusic, AudioEngineService.setRoleDuck) and restores them on pause or end. The widgets play through their own <audio> / <video> elements, not through the engine, so their media need no CORS headers; they follow the reader's master mute.

Playing a track

import { Component, inject } from '@angular/core';
import { AudioEngineService } from '@panelwave/player';
import type { AudioTrack } from '@panelwave/player';

@Component({ /* … */ })
export class ReaderComponent {
  private audio = inject(AudioEngineService);

  async playTheme(): Promise<void> {
    const track: AudioTrack = {
      id: 'main-theme',
      url: 'assets/my-story/audio/theme.mp3',
      role: 'music',
      loop: true,
      volume: 0.8,       // 0–1
      fadeIn: 1500,      // ms
      fadeOut: 1000,     // ms
    };
    await this.audio.play(track);
  }

  stopTheme(): void {
    void this.audio.stop('main-theme', 1000); // fade out over 1 s
  }
}

play() initializes the AudioContext on first use, resumes it if suspended, replaces any active track with the same id, and applies the fade-in. Other playback controls: pause(id), resume(id), stopAll(fadeOutMs?), getActiveTracks(), getPlaybackState(id).

Autoplay policy

Browsers block audible playback before the user interacts with the page. The player handles this in two pieces:

  • AudioEngineService tests the policy when it initializes (isAutoplayAllowed() tells you the result) and exposes resumeContext() to resume a suspended AudioContext — call it from a user interaction (click, key press).
  • UserGestureService listens globally for the first real gesture (pointerdown, mousedown, touchstart, keydown, click — hovering deliberately does not count) and exposes hasInteracted() / userHasInteracted$. Video layers use it: programmatic (on-view) video playback starts muted until a gesture has occurred.

A robust pattern for starting music as early as the browser allows:

import { AudioEngineService, UserGestureService } from '@panelwave/player';

constructor(
  private audio: AudioEngineService,
  private gesture: UserGestureService,
) {
  this.gesture.userHasInteracted$.subscribe(async (interacted) => {
    if (interacted) {
      await this.audio.resumeContext();
      await this.playTheme();
    }
  });
}

Volume and muting

MethodEffect
setMasterVolume(v) / getMasterVolume()Master gain, clamped to 0–1
setRoleVolume(role, v) / getRoleVolume(role)Per-channel gain, clamped to 0–1
setMasterMuted(bool) / isMasterMuted() / masterMuted$Master mute, independent of the master volume (the volume survives a mute/unmute round trip). This is what the toolbar's Audio toggle sets; video layers subscribe to masterMuted$.
setRoleMuted(role, bool) / isRoleMuted(role)Per-channel mute, independent of the channel volume (SFX toggle → sfx, Voices toggle → voiceover).
setTrackVolume(id, v)Per-track gain 0–2 of a playing track (its own gain node between the element and the bus).
isActive(id)Whether a track id is registered (playing or paused).

The signal chain is element → track gain → role gain → master gain → output; fades ramp the track gain, so fading one track never touches its bus.

Sequence tracks

Chapters can define sequence audio tracks (chapter.sequenceAudioTracks) — music, ambience, or voiceover beds positioned on a timeline that spans multiple panels, each with assetId, role, startTime, duration, and optional volume (0–2), loop, fadeIn/fadeOut, playbackRate, muted, a panel range (startPanelId/endPanelId), and span (custom, page, chapter, work; format 1.8.0).

From player 1.6.0, the shell's SequenceAudioService plays them as the reader moves through the panels:

  • Placement follows the CMS timeline: the work is one line of panels — chapters in order, the active page format's pages, reading order — each lasting its durationMs (else settings.ui.secondsPerPanel, else 5 s). A track's startTime is relative to its chapter's start; page / chapter tracks cover their startPanelId..endPanelId range.
  • Entering a panel starts every track that covers it, at the matching offset — jumping into the middle of a scene picks the music up where it would be. A track that starts or ends inside a panel is delayed or stopped there.
  • Continuity: a track keeps playing while the reader stays inside its range, so music doesn't restart on every panel. Leaving the range fades it out (its fadeOut, else 250 ms).
  • Across chapters: a span: "work" track continues into the following chapters until its endPanelId (else the last panel); every other track ends with its chapter.
  • Format filters (format), muted tracks, roles → channels, the reader's Audio/SFX/Speech toggles, locked panels, the cover, and the autoplay-policy retry behave as for panel audio.

The placement helpers (buildWorkTimeline, resolveTrackRanges, cuesForPanel) are exported for hosts. A host that runs its own clock can still start every track audible at a timeline position, seeking each to the correct offset:

// Start all chapter tracks that overlap the 12.5 s mark
await this.audio.playSequenceTracks(
  chapter.sequenceAudioTracks ?? [],
  12_500,                       // current playback time in ms
  'https://cdn.example.com/'    // base URL prepended to each track's assetId
);

// Later
await this.audio.stopSequenceTracks(); // or pass specific track ids

Muted tracks are skipped, per-track volume is clamped to 0–2, and fade-ins are shortened when starting mid-fade.

Video sound

Video layers manage their own audio element state via VideoControllerService (single active video with sound at a time) and default to muted: true; a work can change this with settings.ui.videoMutedDefault or per layer. Reduced motion degrades on-view autostart to click-to-play, which also satisfies gesture requirements. See Video for the format side.

Spoken lines

From player 1.12 (format 1.12 convention) the shell speaks the balloons: a bubble's audioAssetId names an audio asset of the catalog (role voiceover), and BubbleVoiceService plays it on the voiceover channel when the balloon appears — with the panel, or at the balloon's showAtMs on the panel clock (the same clock timed balloons wait on). The lines of a panel play one after another in balloon order, so two balloons shown together never talk over each other; panels shown together (page view, canvas view) read in reading order — in page view the page's readingOrder (from player 2.2.0; before, a page whose placements were not listed in reading order could start with a later panel) — and a later panel waits for an earlier panel's timed line instead of talking in between; a panel that is scrolled away or left stops talking, and entering it again reads it from the top. A tap on a balloon speaks its line again.

A line recorded per language lists one AudioVariant per locale on that one asset; the player picks the take in the reader's language: exact locale → same base language → a variant without locale. From player 2.2.0 a line that has takes only in other languages stays silent — a German reader no longer hears the English take because the German one is missing (1.12–2.1 fell back to meta.default_locale, the way image variants still do). A line without any localized take plays in every language. A line cut short while it is still starting (the host's start language arriving, Voices switched off, the panel left) is stopped as soon as it registers, so it no longer plays on next to the re-read line. Switching the language (or turning the voices on) re-reads the shown panel and marks every other attached panel unread, so a page the reader scrolled away from is spoken in the new language when it comes back. The reader's Voices toggle (seeded from settings.ui.voicesDefault, off unless the work sets it) stops and starts everything; Speech only hides the balloons, so readers can listen without reading. A line the browser's autoplay policy refuses before the first click is spoken on that click.

pw-speech-bubbles still emits bubbleAudioPlay with { bubble, audioAssetId } when a voiced bubble is activated, for hosts that render the overlay without the shell; BubbleVoiceService.replay(bubble) and setEnabled() are the service's public entry points, speaking$ tells which balloon is being spoken.

Cleanup

Call destroy() on the engine if you tear down audio entirely: it stops all tracks, closes the AudioContext, and releases every audio element and source node.