Media and Assets
This page follows a game’s files from the moment a script names them to the moment the player sees or hears them: how a name becomes a URL, how play music turns a file into sound, what the boot preload and the Preload action put in memory, and what the service worker keeps between visits. It goes one level below Architecture; read Statements and Actions first, since every media statement is an action.
What it’s for
A game declares its files by name (monogatari.assets('music', { theme: 'theme.mp3' })) and refers to them by that name in the script ('play music theme loop'). This subsystem is everything between the two:
- the asset registry (
_assets) and theAssetsPathsetting, which together turn a name into a URL; - audio: the Web Audio context, the
AudioPlayerclass and its effects, the Play, Pause and Stop actions, the registry of media players, the volume preferences and the main screen’s music; - video, scenes, backgrounds, images and character sprites, as far as finding their files goes;
- preloading: the engine’s
preload()at boot, the Preload and Unload actions, the loader registry and the caches they fill; - the starter game’s service worker (
dist/service-worker.js).
What a media statement records so that rollback and loading can rebuild it belongs to State, Storage and Rollback and Saving and Loading; this page shows the media side of that contract.
The files
| File | What it does | Cypress specs |
|---|---|---|
src/engine/assets.ts |
assets() and asset(), the image and audio-buffer caches, the persistent audio cache in IndexedDB, the screenshot space, the service worker messages |
actions/preload.spec.js, actions/unload.spec.js |
src/monogatari.ts |
_assets and its default categories, the default AssetsPath, audioContext, _mediaPlayers with mediaPlayer(), mediaPlayers() and removeMediaPlayer(), preload(), ambientPlayer, the service worker registration in setup() |
actions/play.spec.js, actions/preload.spec.js |
src/lib/AudioPlayer.ts |
The Web Audio player: play, pause, stop, fades, volume, loop, the effect registry, the 17 built-in effects and their two audio worklets | actions/play.spec.js, actions/stop.spec.js, actions/pause.spec.js |
src/lib/ElementAudioPlayer.ts |
The same player through an <audio> element, for a page opened from a file or a track the browser won’t let the page read: no effects |
actions/play.spec.js (“When the browser refuses to let the game read the file”) |
src/lib/opened-from-file.ts |
openedFromFile(): a browser opened the game from a file: address (not a desktop app or Cordova) |
none |
src/actions/Play.ts |
`play music | sound |
src/actions/Pause.ts, src/actions/Stop.ts |
pause … and stop …, with fades |
actions/pause.spec.js, actions/stop.spec.js |
src/actions/Video.ts, src/actions/HideVideo.ts |
show video … and hide video … with <video> elements |
actions/show_video.spec.js, actions/hide_video.spec.js |
src/actions/Scene.ts, src/actions/ShowBackground.ts |
show scene … and show background …: a CSS background on [data-ui="background"] |
actions/show_scene.spec.js |
src/actions/ShowImage.ts, src/actions/HideImage.ts |
show image … and hide image … |
actions/show_image.spec.js, actions/hide_image.spec.js |
src/actions/ShowCharacter.ts, src/actions/ShowCharacterLayer.ts, src/components/character-sprite/ |
Sprites and (experimental) layered sprites | actions/show_character.spec.js, actions/show_character_layer.spec.js |
src/engine/characters.ts |
characters() and character(), which translate the old character properties (Images, Directory, Face, Side…) when a character is read |
actions/show_character.spec.js |
src/actions/Preload.ts, src/actions/Unload.ts |
The loader registry, preload blocks, preload … and unload … |
actions/preload.spec.js, actions/unload.spec.js |
src/engine/ui.ts |
playAmbient() and stopAmbient(), the main screen’s music |
none |
src/components/main-screen/index.ts, src/components/loading-screen/index.ts, src/components/settings-screen/index.ts |
Starting and stopping the main screen’s music, the preload progress bar, the volume sliders | actions/play.spec.js (the volume slider) |
dist/service-worker.js |
The starter game’s cache strategy | none |
dist/js/options.js |
The game’s own AssetsPath, Preload, ServiceWorkers and MainScreenMusic |
none |
How it works
From a name to a URL
Two tables meet when an action needs a file. The asset registry, _assets in src/monogatari.ts, maps names to file names per category. It starts with seven empty categories (music, voices, sounds, videos, images, scenes, gallery); assets(type, object) merges names into one, assets(type) reads it, and asset(type, name, value?) reads or writes a single entry. The AssetsPath setting maps the same category names to folders under a root:
'AssetsPath': {
'root': 'assets',
'characters': 'characters',
'icons': 'icons',
'images': 'images',
'music': 'music',
'scenes': 'scenes',
'sounds': 'sounds',
'ui': 'ui',
'videos': 'videos',
'voices': 'voices',
'gallery': 'gallery'
}An action builds ${root}/${AssetsPath[category]}/${file}. settings() merges objects deeply, so a game that sets AssetsPath: { root: 'https://cdn.example.com/game' } keeps every folder name. Each statement uses the category and does something different when the name isn’t declared:
| Statement | Category and folder | When the name isn’t declared |
|---|---|---|
play music <name> |
music |
The name is used as the file name |
play sound <name>, play voice <name> |
sounds, voices (Play adds an s to the type) |
The name is used as the file name |
show scene <name>, show background <name> |
scenes |
The words are used as a CSS value: #555555, red, a gradient |
show image <name> |
images |
The name is used as the file name |
show character <id> <sprite> |
characters, then the character’s directory, then sprites[sprite] |
An error dialog: action:show_character:sprite_not_found |
show character <id>:<layer> <name> |
characters, then the character’s directory, then layer_assets[layer][name] (an experimental action) |
An error dialog |
show video <name> <mode> |
videos |
The URL ends in undefined |
MainScreenMusic |
music |
An error dialog: engine:music:not_defined |
| The gallery screen | gallery |
The screen lists only the declared names |
Canvas objects and particle systems are configured on their actions (monogatari.action('Canvas').objects(), monogatari.action('Particles').particles()) and load no files of their own. Side images in dialog (expressions) are covered in Text and the Type-Writer.
The rule under all of this: the category name, the AssetsPath key and the cache prefix are the same string. play sound beep looks up assets.sounds.beep, fetches from AssetsPath.sounds, and looks for sounds/beep in the audio cache.
Playing a sound: from statement to speaker
play music theme loop runs through the Play action like this:
The pieces, in the order they run:
- The audio context.
Play.setup()createsengine.audioContextonce (window.AudioContext, orwebkitAudioContextwhere only that exists) and, unlessopenedFromFile(), callsAudioPlayer.initialize(), which loads two AudioWorklet modules (bitcrusher-processor,envelope-follower-processor) from Blob URLs; Chrome refuses those on afile:page. A context created before the player clicks anything starts suspended;AudioPlayer.play()callsaudioContext.resume()when it finds it so. - The constructor splits the words as
[action, type, media, ...props]. Whenmediais missing or iswith, the statement names no track (mediaKeystaysundefined, and awithgoes back into the words): it means “every player of this type” (play musicresumes all paused music) andthis.playeris the array frommediaPlayers(type). Otherwise it reuses a registered player with that name or leavesnullforapply(). A type that isn’tmusic,soundorvoicemakeswillApply()showaction:play:invalid_type, and the statement records nothing. apply()reads the words:loop,fade <seconds>,volume <percent>and any registered effect name.withis filler. The volume ispreference('Volume')[Music|Sound|Voice] × percent / 100, and the percentage is kept inplayer.dataset.volumePercentageso the volume slider can scale the player later.createAudioPlayer()takes the decoded buffer fromaudioBufferCache('<category>/<name>')when the Preload action put it there. Otherwise, opened from a file, it returns anElementAudioPlayerat once; served, it fetches the file, and when the browser refuses thefetch()(another site without CORS headers) it falls back to anElementAudioPlayertoo. A response that isn’tok, a file that won’t decode, or an<audio>element that fireserrorthrows:apply()showsaction:play:load_failedwith the address and the reason, marks the statementfailed, and the game goes on without the track. A decoded buffer gets a gain node connected toaudioContext.destination, which theAudioPlayeruses as its output.- The player is registered under
mediaPlayer(type, name), which also writesdataset.typeanddataset.keyon it.onended(for a track that doesn’t loop) removes the track’s item from the state and the player from the registry. didApply()pushes the statement intohistory(type), appends{ statement, paused }tostate(type), and returns{ advance: true }: a play statement never waits.
A name that’s already registered doesn’t start over. apply() sets replacing: when the statement has other words than with and fade <seconds>, its loop and volume replace the track’s, and a paused track resumes (with fade, fading in). didApply() keeps one state item per track: it replaces the track’s item (with the new statement, or the old one when the new one had no words of its own) and records the item it replaced.
Pause pauses one player or all of a type, the ones that were playing, and marks their state items paused: true; a named player that doesn’t exist (the track isn’t playing) leaves nothing to pause, and the statement goes on. Stop turns looping off in willApply(), waits for fadeOut() of every player at once when given with fade <seconds>, and removes the players with removeMediaPlayer(); stopping every player of a type pushes the whole state array into the history so a rollback can restore it. removeMediaPlayer() calls destroy() on an AudioPlayer, or pauses an HTML media element, removes its src attribute and calls load(). (Setting src to '', as it did before 2.9.0, makes the element fire an error event, code 4, in Chromium and Firefox.)
What the statements changed, for going back. Each pause, plain play <kind>, play of a track already there and named stop pushes one MediaChangeItem to history('mediaChanges') when it runs ({ type, paused: [names] }, { type, resumed: [names] }, { type, name, replaced }, { type, name, stopped: [items] }). Its revert() reads the last one and its didRevert() pops it. Rollback reverts statements in the reverse order they ran, so the last record is always the one of the statement being reverted. A statement that ran before 2.9.0, in a game loaded from an older save, finds no record and goes back the old way.
Voices have two extra rules in Play’s static hooks. shouldProceed() refuses to advance while a voice is still playing, but only when the advance wasn’t the player’s own and isn’t skip: auto-play waits for the line to finish, a click doesn’t. willProceed() and willRollback() call shutUp(), which removes every voice player and empties state.voice, so a click cuts the voice off.
On rollback, each action’s revert() undoes its own work (Play removes the player it created or puts a replaced track back as it was, a plain play pauses what it resumed, Pause resumes what it paused, Stop replays what it removed): see State, Storage and Rollback. On load, Play.onLoad() keeps one item per track name (a save from before 2.9.0 could hold one twice) and runs each through prepareAction(), willApply(), apply({ paused }) and didApply({ updateHistory: false, updateState: false }), all at once; a paused one is created paused and never starts: see Saving and Loading.
Inside AudioPlayer
AudioPlayer wraps one decoded AudioBuffer. An AudioBufferSourceNode can only be started once, so play() builds a new source node every time, connects it through the effect chain to the output gain node, and starts it at an offset: pausedAt when resuming, 0 otherwise. pause() records how far it got and tears the source down; stop() resets the offset.
It exposes the same names as an HTMLMediaElement (paused, ended, volume, loop, currentTime, duration, dataset, onended) so that removeMediaPlayer(), the volume listener and shouldProceed() can treat audio players and <video> elements alike. A few behave differently:
volumesets the gain withsetValueAtTime(); it can be above 1.fadeIn(duration, target)sets the gain to 0 and ramps it linearly totarget;fadeOut(duration, stopAfterFade)ramps to 0. Both return at once when the player isn’t playing, and both wait for the fade with asetTimeout.destroy()stops, disconnects the output and dropsonended. It is whatremoveMediaPlayer()calls.
Effects live in a static registry. AudioPlayer.effect(id, configuration) registers one, AudioPlayer.effect(id) reads it and AudioPlayer.effects() lists them. Seventeen are built in: filter, delay, compressor, tremolo, distortion, convreverb, bitcrusher, autowah, panner, phaser, chorus, wah, ringmod, saturator, limiter, fadein and fadeout. Each has a create(audioContext, params) that returns either an AudioNode or { node, output?, stop?, disconnect? } for effects made of several nodes or that own oscillators or constant sources: the sound goes into node and comes out of output (delay, chorus, phaser and ringmod join a dry and a wet path in an output gain node, and autowah comes out of its filter).
Play.parseEffects() finds every registered effect id among the statement’s words and fills its params from the words after it, in order, turning each into a number when parseFloat() can. createEffectChain() then connects the source to each effect’s node in turn, continues from its output (or its node), and connects the last one to the output gain node.
ElementAudioPlayer extends AudioPlayer and overrides every public member to drive an <audio> element instead: play(), pause() and stop() call the element’s, volume and loop are the element’s (the volume clamped to 0 to 1), and the fades step the element’s volume every 50 ms. ElementAudioPlayer.load() waits for loadedmetadata, or rejects on the element’s error, so Play can report the file. A NotAllowedError from play() (the browser’s autoplay rule) starts the track on the next pointerdown. It keeps the effects it’s given and applies none; the first player with effects logs a warning.
Volume and the settings screen
The settings screen renders four range inputs with data-action="set-volume" and data-target set to music, sound, voice or video. Play.init() sets their starting values from preference('Volume'), and the settings screen sets them again on didInit, so a game that replaces the Play action still shows the player’s volumes (until 2.9.0 the screen’s own loop looked for elements that don’t exist). Play.bind() registers the set-volume listener, which the engine’s [data-action] click handler runs:
- for
video, it setsvolumeon every[data-video]element; - for the others, it sets each player’s volume to the slider’s value times the player’s
volumePercentage, and formusicalso the main screen’s player; - it stores the new value in the preferences with
preferences(preferences(), true).
Video reads Volume.Video when it creates each element.
Music on the main screen
The main screen’s music doesn’t go through Play. init() creates engine.ambientPlayer as a plain new Audio() element. The main screen component calls playAmbient() when it opens and stopAmbient() when it closes during a game; Jump.willApply() stops it too. playAmbient() looks MainScreenMusic up in the music category (showing engine:music:not_defined when it isn’t there), sets the volume from the music preference, loops, and calls play(). When the browser blocks autoplay it prepends a [data-ui="broadcast"][data-content="allow-playback"] message that starts the music when clicked.
Because it is an <audio> element that streams its file, the main screen’s music plays in a page opened from a file. Since 2.9.0, play music does too, through an ElementAudioPlayer. See What works opened from a file.
Video
Video creates a <video> element with src set to ${root}/${videos}/${asset}, data-video set to the name and data-mode to one of modal, displayable, immersive, fullscreen or background. Video.parse() reads the words: the mode is the word after the name, or modal when that word is with, close, loop or controls; the state and the history are matched with the same reading (Video.describes()). Background videos go into [data-ui="background"], the others into the game screen. Modal, immersive and fullscreen set the static Video.blocking, and Video.shouldProceed() refuses to advance while it is set or while a video in one of those modes still plays (waitingVideoPlaying()).
When the element ends, blocking is recomputed; with close the element also goes and, for immersive and fullscreen videos, the game proceeds (a modal one already let the next statement run). Without close, Video.willProceed() removes a waiting video that ended when the player moves on, and Video.willRollback() removes an immersive or fullscreen one, which is the statement the player is on. An element that fires error goes too, and unblocks the game. hide video recomputes blocking, and records in history('hideVideo') the statement of the video it removed (or null), so its revert shows only what it hid. Video uses the media element, not Web Audio, and the Preload action has no loader for it. Show Video has the statement’s syntax.
Scenes, backgrounds, images and sprites
show scene <name>runsshow backgroundwith the same words, then removes every character and image from the screen (unless a load is restoring the state).ShowBackgroundsetsbackground-image: url(…)on[data-ui="background"]for a declared scene, and otherwise uses the words as a CSS value,background-colorwhen it looks like a color.show image <name>builds an<img>and appends itsouterHTMLto[data-screen="game"] [data-content="visuals"]. WhenimageCache('images/<name>')holds a preloaded element, it clones that element instead of creating a new one.show character <id> <sprite>finds the file in the character’ssprites, undercharacters/<directory>/. A sprite already on screen has itssrcchanged; a new one is cloned fromimageCache('characters/<id>/<sprite>')when that exists.src/engine/characters.tstranslates the old property names (Images→sprites,Directory→directory,Face→default_expression,Side→expressions,Color,Name,TypeAnimation) the first time a character is read.
Neither Scene nor ShowBackground reads the image cache: a CSS background is fetched by the browser, which uses its own HTTP cache.
Preloading at boot: preload()
displayInitialScreen() calls engine.preload() once the engine has mounted, and shows the splash or main screen when it settles, whether it succeeded or not.
- With a
defaultblock (monogatari.action('Preload').blocks({ default: { … } }), set beforeinit()), only the block’s assets load, through the same loaders as the Preload action, into the engine’s caches: decodedAudioBuffers for audio categories, decodedHTMLImageElements for image categories.assetLoadedcarries{ name, type, category }with the asset’s name and the loader type (audio,image). - Without one, every declared asset of every category is requested: images with Artemis’
Preload.image()(which decodes them), everything else withPreload.file()(afetch()with low priority). Then each character’ssprites,expressionsandlayer_assets, and itsdefault_expressiononly when that names a file rather than one of itsexpressions(Dialogreads it both ways). ASetof addresses keeps a file declared twice, like a sprite that is also an expression, to one request. The browser keeps them in its HTTP cache (and the service worker in its own); the engine’s caches stay empty, so the firstplay musicstill fetches and decodes.assetLoadedcarries the file name andimageorfile.
Every file goes through one helper inside preload(), queue(): it fires assetQueued, starts the load, and when the load settles fires assetLoaded or, with the address and the error, assetFailed. Each queued file finishes exactly once, and no load rejects the Promise.all(), so didPreloadAssets always fires. The failed addresses are logged one by one and listed in one engine:preload:files_not_loaded dialog after didPreloadAssets.
The loading screen opens on willPreloadAssets (and puts max and progress back to 0), adds one to its progress bar’s max on each assetQueued, one to its value on each assetLoaded or assetFailed, and closes on didPreloadAssets. It sets the <progress> element’s value property itself: Artemis’ value() only writes to form fields.
Before 2.9.0 the legacy path queued one asset per character but loaded one per picture, the bar never moved (it went through value()), a default_expression naming an expression was requested as a file (assets/characters/yui/normal, a 404 and an EncodingError in every game with one), and that one failure kept didPreloadAssets from firing.
The Preload and Unload actions
Preload.setup() fills three registries the first time it runs:
- loaders:
audio(look in the persistent IndexedDB cache, otherwisePreload.audio()from Artemis, which fetches and decodes with the engine’s audio context, then store the buffer in IndexedDB without waiting) andimage(Preload.image()), each with acacheaccessor ofget,set,deleteandclear; - categories:
music,sounds,voicesuseaudio;scenes,images,charactersuseimage; - aliases:
scene,image,soundandvoicein a statement mean the plural category.
preload <category> <name> [blocking], preload character <id> <sprite> [blocking] and preload block <id> [blocking] start the load in apply() and wait for it only with blocking. An asset whose key is already cached is skipped; a failure is logged with console.error and the game goes on. The action always returns { advance: true } and its revert() does nothing.
unload takes the same forms plus unload <category> (the whole category) and unload all. It removes entries from the memory caches; with the word permanent it also removes audio from the IndexedDB cache. unload all permanent, and unload of a whole audio category with permanent, clear the entire persistent audio cache, since its keys are URLs and can’t be filtered by category.
The caches
| Cache | Keys | Filled by | Read by | Emptied by |
|---|---|---|---|---|
imageCache(), a Map of HTMLImageElement |
scenes/<name>, images/<name>, characters/<id>/<sprite>, <custom category>/<name> |
the image loader (Preload action, default block) |
ShowImage (images/…), ShowCharacter (characters/…) |
imageUncache(), imageClearCache(prefix), clearAllCaches(), the Unload action |
audioBufferCache(), a Map of AudioBuffer |
music/<name>, sounds/<name>, voices/<name> |
the audio loader |
Play.createAudioPlayer() |
audioBufferUncache(), audioBufferClearCache(prefix), clearAllCaches(), the Unload action |
Persistent audio: IndexedDB database <game name>_AudioCache, store decodedAudio |
the file’s URL | the audio loader (storeAudioBufferPersistent()) |
the audio loader only (getAudioBufferPersistent()) |
unload … permanent, clearAudioBufferPersistent() |
Cache Storage <name> <scope> v<version> (Monogatari https://example.com/my-game/ v0.1.1) |
request URLs | the service worker | the service worker, and the dev server’s live reload, which deletes changed files | a new VERSION in service-worker.js |
The two memory caches last as long as the page. The persistent audio cache survives a reload, but only the Preload action’s loader reads it: after unload music theme, play music theme fetches the file from the network again, while preload music theme restores it from IndexedDB without a request. The database name is the game’s Name setting passed through Artemis’ Text.friendly() (My Visual Novel becomes my-visual-novel_AudioCache). The screenshot space next to it belongs to Saving and Loading.
The service worker
setup() registers ./service-worker.js when the ServiceWorkers setting is on, the game isn’t in Electron, Electrobun or Cordova, and the browser supports service workers. On a file: page it logs a warning instead. When a new worker finishes installing while an old one controls the page, the engine prepends a “new content” broadcast asking the player to reload.
The worker in dist/service-worker.js belongs to the starter game, not to the engine bundle: every game ships its own copy.
- Scope. Every path is relative to the worker’s own folder,
self.registration.scope: theFILESlist starts with'./', and the assets folder isASSETS_URL, theASSETSconstant resolved against that scope (changeASSETSfor a game whoseAssetsPath.rootisn’tassets). Until 2.9.0 the list started with'/'and assets were recognised by a path starting with/assets/: in a sub-folder whose site root didn’t answer 200,addAll()failed and no worker installed; where it did install, game media fell to network first. - Install keeps each file of the
FILESlist with its owncache.add()(withcache: 'no-cache'), so a file missing on the host is skipped and named in a console warning instead of failing the install, and callsskipWaiting(). - Cache name.
`${NAME} ${SCOPE} v${VERSION}`: each game on an origin has its own, so two games that keep the starter’sNAMEno longer share one cache or delete each other’s. Activate deletes this game’s caches of other versions, deletes this game’s entries (URLs under its scope) from a 2.8-style${name}-v<version>cache, and that cache itself once it’s empty, then claims the open pages. - Network first (the page, the engine,
js/,style/, anything same-origin outside the assets folder) fetches withcache: 'no-cache', so the browser’s HTTP cache revalidates with the server and an edited file is used at once; offline, the cached copy answers. Navigations are fetched as they are (a navigation request can’t be copied with new options). - Cache first (the assets folder) answers from the cache, then, in
event.waitUntil(), sends one conditional request per file per page load (If-None-MatchandIf-Modified-Sincefrom the cached copy,cache: 'no-store') and stores a200; a304costs a few bytes. A cached response with neither validator isn’t checked. Until 2.9.0, a replaced asset was served from the cache untilVERSIONchanged. - Responses the page gets carry
Cache-Control: no-cache, so the renderer’s own memory cache asks the worker again on the next load instead of reusing a file it loaded a moment ago (Chromium did, for files whoseLast-Modifiedwas days old). - Only
200responses of typebasictoGETrequests are stored, written while the page reads the response. - Messages
CACHE_ASSETS,CHECK_CACHEandGET_CACHEDanswer the engine’scacheInServiceWorker(),isInServiceWorkerCache()andgetFromServiceWorkerCache(). Nothing in the engine calls these three today; they are there for games.
The data
The effect and player types, from src/lib/types/index.ts:
interface AudioEffectConfig {
id: string;
description: string;
params: string[];
create: (audioContext: AudioContext, params: Record<string, unknown>) => AudioNode | AudioEffectResult;
}
interface AudioEffectResult {
node: AudioNode;
stop?: () => void;
disconnect?: () => void;
}
interface AudioPlayerOptions {
outputNode?: GainNode | null;
effects?: Record<string, Record<string, unknown>>;
loop?: boolean;
paused?: boolean;
volume?: number;
}What the media actions record, from the same file:
interface MediaStateItem {
statement: string;
paused: boolean;
}
// What history('music' | 'sound' | 'voice') holds: a played statement,
// or the whole state array that a 'stop music' (without a name) removed.
type MediaHistoryItem = string | MediaStateItem[];
interface StateMap {
music: MediaStateItem[];
sound: MediaStateItem[];
voice: MediaStateItem[];
scene: string;
background: string;
characters: string[];
images: string[];
videos: string[];
// …
}The AssetsPath setting, from src/lib/types/GameSettings.ts:
AssetsPath: {
root: string;
characters: string;
icons: string;
images: string;
music: string;
scenes: string;
sounds: string;
ui: string;
videos: string;
voices: string;
gallery: string;
}The loader registry, from src/actions/Preload.ts:
type AssetLoader<T = unknown> = (url: string, engine: VisualNovelEngine) => Promise<T>;
type AssetCacheAccessor<T = unknown> = {
get: (engine: VisualNovelEngine, key: string) => T | undefined;
set: (engine: VisualNovelEngine, key: string, value: T) => void;
delete?: (engine: VisualNovelEngine, key: string) => void;
clear?: (engine: VisualNovelEngine, prefix: string) => void;
};
type LoaderConfig<T = unknown> = {
loader: AssetLoader<T>;
cache: AssetCacheAccessor<T>;
};
interface PreloadBlock {
music?: string[];
sound?: string[];
voice?: string[];
scenes?: string[];
images?: string[];
characters?: Record<string, string[]>; // { characterId: [sprite names] }
[category: string]: string[] | Record<string, string[]> | undefined;
}And the player registry on the engine, from src/monogatari.ts: one object per type, keyed by the name the statement used.
static _mediaPlayers: Record<string, Record<string, HTMLAudioElement | HTMLVideoElement | AudioPlayer>> = {
music: {},
sound: {},
voice: {},
video: {}
};Rules and why
- One string names a category everywhere. The asset category, the
AssetsPathkey and the cache prefix must match (sounds, neversound, outside a statement). Play builds it by adding ans, Preload by its aliases; a new category needs an entry in all three places. - State holds statements, never URLs or objects. A media state item is the statement that made it, replayed through
prepareAction()on load. Changing an asset’s file name orAssetsPathbetween versions doesn’t break old saves for that reason. - One player per type and name.
mediaPlayer(type, name, player)overwrites the entry without stopping the old player. Remove a player withremoveMediaPlayer()before registering another under the same name, or it plays on with nothing able to stop it. - Remove players through
removeMediaPlayer(). It callsdestroy(), which disconnects the gain node; dropping the reference leaves the node connected to the destination. - Media statements don’t wait. Play, Pause, Stop and Preload return
{ advance: true }. What holds the game is a veto inshouldProceed()(a voice under auto-play, a blocking video) or a blocking preload’sawaitinapply(). - Web Audio needs the file’s bytes. Play fetches and decodes, so effects need an
http:orhttps:page; on afile:page the track falls back to an<audio>element, which streams. Any new code that reads a file’s data needs the same fallback: checkopenedFromFile(). - An effect’s sound comes out of
output, or ofnode.createEffectChain()connects intonodeand continues fromoutputwhen the effect gives one. An effect made of several nodes has to name the node its paths join in, or the chain carries its input unchanged (Exercise 3 is that bug). - A media statement that changes a track already there leaves one record. Every
pause, plainplay,playof a registered name and namedstoppushes exactly onemediaChangesitem when it runs and pops it when reverted. A new statement of that kind must do the same, or the next revert reads someone else’s record.
How to make the common changes
Add a built-in audio effect
Register it at the end of src/lib/AudioPlayer.ts, list its params in the order a statement gives them, and return a node that carries the result:
AudioPlayer.effect('gain', {
description: 'Scales the signal by a fixed amount',
params: ['amount'],
create: (audioContext, { amount = 1 }) => {
const node = audioContext.createGain();
node.gain.value = amount as number;
return node;
},
});When the effect owns oscillators or constant sources, return { node, stop, disconnect } so cleanup() stops them with the player. Add a test to cypress/e2e/actions/play.spec.js, and document it on Play Music. A game registers its own effects the same way, through Monogatari.AudioPlayer.effect() in js/main.js.
Add an asset category the Preload action can load
Register the category against an existing loader, give it a folder and declare its assets:
monogatari.action('Preload').registerCategory('posters', 'image');
monogatari.settings({ 'AssetsPath': { 'posters': 'posters' } });
monogatari.assets('posters', { 'opening': 'opening.png' });preload posters opening then fills imageCache('posters/opening'). A new kind of file needs a loader with its own cache: the engine has caches for images and audio buffers only, so keep the store next to the loader.
const videos = new Map();
monogatari.action('Preload').registerLoader('video', {
loader: (url) => fetch(url).then((response) => response.blob()),
cache: {
get: (engine, key) => videos.get(key),
set: (engine, key, value) => videos.set(key, value),
delete: (engine, key) => videos.delete(key),
clear: (engine, prefix) => {
for (const key of videos.keys()) {
if (key.startsWith(prefix)) {
videos.delete(key);
}
}
},
},
});
monogatari.action('Preload').registerCategory('videos', 'video');Nothing reads that cache until an action does: the Video action builds its URL from AssetsPath every time.
Make an action use the image cache
Follow ShowImage: build the key from the category and the name, clone the cached element when there is one, and fall back to a new element with the URL.
const cached = this.engine.imageCache(`images/${this.asset}`);
const image = cached ? cached.cloneNode(true) as HTMLImageElement : document.createElement('img');
if (!cached) {
image.src = `${this.engine.setting('AssetsPath').root}/${this.engine.setting('AssetsPath').images}/${this.image}`;
}Change what the service worker caches
Edit dist/service-worker.js (it ships with every game made from the starter, and an engine update doesn’t replace a game’s copy, so say in the release notes what games should copy), and test it served, with the browser’s application panel open, in Chromium and Firefox. The cases that broke before: a game in a sub-folder whose site root answers 404 (install, then play with the server stopped), two games in two folders of one origin, an edited stylesheet (it must show on the first reload) and a picture replaced under the same name (by the second). Use a server that sends ETag or Last-Modified and answers conditional requests with 304, and date the game’s files a few days back first: browsers keep a file fresh for longer the older its Last-Modified is, which is when stale files show.
Pitfalls and history
- Audio moved to Web Audio in 2.8.0. Until
b969c5a4(“Use audio API instead of audio elements”, July 2025) Play usednew Audio();abb73e68then made the effects a registry. Released in 2.8.0, the change brought the effects, and it meantplay musicdidn’t work in a page opened from a file: thefetch()was refused,apply()rejected and the run stopped. 2.9.0 addedElementAudioPlayerfor that case. - 2.8.x showed no dialog when an audio file couldn’t load.
createAudioPlayer()didn’t checkresponse.okand didn’t catch: a missing file ended in a console error and a game stopped on an empty line. 2.9.0 addedaction:play:load_failedand lets the game go on (Exercise 4 is that change). - 2.8.x fumbled resumes and replays. The resume path called
fadeIn()beforeplay(), soplay music with fade 2resumed at full gain; the constructor storedmediaKey = 'with', adding a bogus state item; playing a registered name appended a second state item, so a load created two players and one played with nothing able to stop it; and going back past a plainplaypaused every track. 2.9.0 fixed them all, with themediaChangesrecords. - 2.8.x’s
delay,chorus,phaser,ringmodandautowahdid nothing. They returned their input node, the chain continued from it, and the output was the dry signal. 2.9.0 addedoutput(Exercise 3 is that change). - Effect parameters are positional.
play music theme with filter lowpass 400 loopgives the filterQ = 'loop'; setting anAudioParamto a string throws, the chain logs “Error creating effect ‘filter’” and skips the filter (the music still loops). Put effects last and give them every parameter. The old Play Music page says the order of the words doesn’t matter. - Blocks need plural categories.
PreloadBlocklistssoundandvoice, but neitherpreloadBlock()norpreload()resolves aliases:{ sound: ['beep'] }loads nothing and logs “No loader registered for category “sound”“. Usesoundsandvoices. - A video name must be declared. Unlike images and audio,
show video clip.mp4 …with noclip.mp4entry buildsassets/videos/undefined; the element’serrorremoves it, and the console says Failed to load video. - Every first preload of a sound logs a warning.
getAudioBufferPersistent()treats a cache miss (KeyNotFoundError) as a failure and logs “Failed to retrieve audio buffer from IndexedDB”. The game works; the console is noisy. - The service worker assumed it was at the site’s root until 2.9.0, and served replaced media from its cache until
VERSIONchanged (see The service worker). Games keep their own copy ofservice-worker.js, so games started before 2.9.0 still have that worker until they copy the new one. - Firefox keeps a stylesheet it loaded before the worker controlled the page. On the visit that installs the worker,
style/main.csscomes from the network with the host’s headers; Firefox’s stylesheet cache then reuses it, without asking the worker, for as long as those headers make it fresh (aLast-Modifieddays old and noCache-Control: hours). It does the same with no worker at all. After a browser restart the page is controlled from the start and edits show on reload. show_scene.spec.jsfailed on a clean 2.8.1 checkout. Its last test expected backgrounds fromdatadyne.perfectdark.space, whilecy.loadTestAssets()points atdatadyne.hyuchia.com(load-screen.spec.jshad the same expectation). 2.9.0 fixed both specs.
Exercises
In a scratch copy of the repository (How Each Part Works), write each check as a spec in cypress/e2e/exercises/ and run it with bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/<file>'; delete it when you are done. cy.loadTestAssets() points the game at the project’s test files online, so the machine needs internet. cy.open() doesn’t wait for the engine’s init(): wait for main-screen to be visible (or click Start with cy.start()) before reading anything the mount sets up. Exercises 3 and 4 change src/ to fix bugs that 2.9.0 fixed the same way: make their scratch copy from the v2.8.1 tag (git worktree add --detach ../monogatari-exercises v2.8.1), rebuild the bundle Cypress loads before running the spec, and put everything back afterwards with git checkout -- src debug dist/engine.
Exercise 1: add an audio effect a script can use
What to do. Without touching src/, register an effect called gain with one parameter, amount, that scales the sound, and play 'play music theme gain 0.5 loop'. The effect must receive amount: 0.5, and the music must loop.
Hint. The page’s window.Monogatari exports AudioPlayer. Read Play.parseEffects() to see which words become parameters, and count how many words gain takes before loop.
Check. The spec records what create() receives. It passes with the effect registered; without the registration, create() is never called and the check fails.
Solution
context('Exercise: a custom audio effect', () => {
beforeEach(() => {
cy.open();
cy.loadTestAssets();
});
it('Builds the effect from the words after its name', function() {
cy.window().then((win) => {
const { AudioPlayer } = win.Monogatari;
win.receivedParams = [];
AudioPlayer.effect('gain', {
description: 'Scales the signal by a fixed amount',
params: ['amount'],
create: (audioContext, { amount = 1 }) => {
win.receivedParams.push({ amount });
const node = audioContext.createGain();
node.gain.value = amount;
return node;
},
});
});
this.monogatari.setting('TypeAnimation', false);
this.monogatari.script({
'Start': [
'play music theme gain 0.5 loop',
'Playing.',
'end',
],
});
cy.start();
cy.get('text-box').contains('Playing.');
cy.window().its('receivedParams').should('deep.equal', [{ amount: 0.5 }]);
cy.wrap(this.monogatari).invoke('mediaPlayer', 'music', 'theme').then((player) => {
expect(player.isPlaying).to.equal(true);
expect(player.loop).to.equal(true);
});
});
});gain declares one parameter, so 0.5 becomes amount and loop stays a word for Play. With params: ['amount', 'curve'], loop would become curve as the string 'loop'. The effect is registered before Start because parseEffects() only looks for ids that are registered when the statement runs.
Exercise 2: preload with the default block
What to do. Show that the legacy boot preload leaves the engine’s caches empty, and that a default block fills them: the scene christmas as a decoded image, the music theme as a decoded AudioBuffer.
Hint. displayInitialScreen() calls the public preload(); you can call it again once the main screen is up. Read which branch of preload() puts things in imageCache() and audioBufferCache(), and what their keys look like.
Check. With the block, both caches hold the assets and assetLoaded fired once per asset with the loader types image and audio. Without the block the image assertion fails.
Solution
context('Exercise: the default preload block', () => {
beforeEach(() => {
cy.open();
cy.loadTestAssets();
// cy.open () doesn't wait for init (): the main screen shows once the
// engine mounted every action and ran the boot preload.
cy.get('main-screen').should('be.visible');
});
it('Fills the engine caches', function() {
const loaded = [];
this.monogatari.on('assetLoaded', (event) => loaded.push(`${event.detail.category}:${event.detail.type}`));
this.monogatari.action('Preload').blocks({
default: {
scenes: ['christmas'],
music: ['theme'],
},
});
// The same call displayInitialScreen () makes while the game boots.
cy.wrap(null).then(() => this.monogatari.preload());
cy.wrap(null).then(() => {
expect(this.monogatari.imageCache('scenes/christmas')).to.have.property('tagName', 'IMG');
expect(this.monogatari.audioBufferCache('music/theme')).to.have.property('numberOfChannels');
expect(loaded.sort()).to.deep.equal(['music:audio', 'scenes:image']);
});
});
});The assertions read properties instead of using instanceOf: the spec runs in a different window than the game, and HTMLImageElement in the spec is not the game’s.
Waiting for the main screen matters. Right after cy.open() the engine may still be mounting: a preload() call then finds no loaders (Preload.setup() hasn’t run), loads nothing and fires didPreloadAssets, and the engine’s own boot preload, still pending, picks the block up a moment later. In a game, set the block in js/script.js or js/main.js, before init(), and the boot preload uses it.
Exercise 3: make the delay audible
What to do. Render a single click through an AudioPlayer with delay (time 0.25, feedback 0, mix 0.5) and confirm there is no echo. Then change the engine so an effect can return a separate output node, and make delay use it.
Hint. An OfflineAudioContext renders without speakers. createSourceNode() and createEffectChain() are private in TypeScript only, so a test can call them. In createEffectChain(), look at which node becomes currentNode after an effect, and where the delay effect’s merger is connected to.
Check. At half mix, the rendered buffer has the dry click at 0.5 at sample 0 and the echo at 0.5 a quarter of a second later. On the v2.8.1 tag the first assertion fails with “expected 1 to be close to 0.5”. 2.9.0’s fix is the same, in src/lib/AudioPlayer.ts, tested in play.spec.js (“Audio effects”).
Solution
The spec:
context('Exercise: an audible delay', () => {
beforeEach(() => {
cy.open();
});
it('Adds an echo after the delay time', () => {
cy.window().then(async (win) => {
const { AudioPlayer } = win.Monogatari;
const sampleRate = 8000;
const context = new win.OfflineAudioContext(1, sampleRate, sampleRate);
// One second of silence with a single click at the start.
const buffer = context.createBuffer(1, sampleRate, sampleRate);
buffer.getChannelData(0)[0] = 1;
const output = context.createGain();
output.connect(context.destination);
const player = new AudioPlayer(context, buffer, {
outputNode: output,
effects: { delay: { time: 0.25, feedback: 0, mix: 0.5 } },
});
// What play () does, without resuming the context: an offline
// context renders when startRendering () is called.
player.sourceNode = player.createSourceNode();
player.createEffectChain();
player.sourceNode.start(0);
const rendered = await context.startRendering();
const samples = rendered.getChannelData(0);
const echo = samples[Math.round(0.25 * sampleRate)];
expect(samples[0], 'the dry click, at half volume').to.be.closeTo(0.5, 0.01);
expect(echo, 'the echo, 0.25 s later').to.be.closeTo(0.5, 0.01);
});
});
});The change: an optional output on AudioEffectResult, used by the chain when present, and returned by delay.
--- a/src/lib/types/index.ts
+++ b/src/lib/types/index.ts
export interface AudioEffectResult {
node: AudioNode;
+ output?: AudioNode;
stop?: () => void;
disconnect?: () => void;
}
--- a/src/lib/AudioPlayer.ts
+++ b/src/lib/AudioPlayer.ts
const effect = configuration.create(this.audioContext, params || {});
let effectNode: AudioNode;
+ let outputNode: AudioNode;
// Handle complex effects that return an object with a node and lifecycle methods
if (effect && typeof (effect as AudioEffectResult).node !== 'undefined') {
const complexEffect = effect as AudioEffectResult;
effectNode = complexEffect.node;
+ outputNode = complexEffect.output ?? complexEffect.node;
if (typeof complexEffect.stop === 'function' || typeof complexEffect.disconnect === 'function') {
this.stoppableResources.push(complexEffect);
}
} else {
effectNode = effect as AudioNode;
+ outputNode = effectNode;
}
if (effectNode instanceof AudioNode) {
currentNode.connect(effectNode);
- currentNode = effectNode;
+ currentNode = outputNode;
this.effectChainNodes.push(effectNode);
+
+ if (outputNode !== effectNode) {
+ this.effectChainNodes.push(outputNode);
+ }
}
@@ AudioPlayer.effect('delay', {
return {
node: inputGain,
+ output: merger,
disconnect: () => wetGain.disconnect(),
};Rebuild and run:
bunx tsc --noEmit
bun build.ts --browser
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/audible-delay.spec.js'
bunx cypress run --browser chromium --spec 'cypress/e2e/actions/play.spec.js'Pushing the output node into effectChainNodes lets cleanup() disconnect it with the rest. chorus, phaser, ringmod and autowah need the same one-line change to return their merger or filter as output.
Exercise 4: report a music file that can’t be loaded
What to do. On the v2.8.1 tag, declare lost: 'lost.mp3' in the music category (the file doesn’t exist) and play it. Nothing tells the player or the developer what went wrong. Make the engine show an error dialog that names the file, and keep the state free of the failed track.
Hint. Error dialogs are templates registered by the debug module in debug/index.js and shown with FancyError.show(id, context). A fetch() of a missing file resolves; look at response.ok.
Check. After Start, a .fancy-error dialog contains lost.mp3 and state('music') is empty. Without the change no dialog appears and the spec times out on .fancy-error. 2.9.0 made the same change, and goes one step further: apply() catches the error instead of rethrowing it, so the game goes on without the track (play.spec.js, “Shows an error naming a file that does not load, and goes on”).
Solution
The spec:
context('Exercise: a music file that does not load', () => {
beforeEach(() => {
cy.open();
cy.loadTestAssets();
});
it('Shows an error dialog naming the file', function() {
this.monogatari.assets('music', {
'lost': 'lost.mp3',
});
this.monogatari.setting('TypeAnimation', false);
this.monogatari.script({
'Start': [
'play music lost',
'After the music.',
'end',
],
});
cy.start();
cy.get('.fancy-error').should('contain', 'lost.mp3');
cy.wrap(this.monogatari).invoke('state', 'music').should('deep.equal', []);
});
});In src/actions/Play.ts, import FancyError next to AudioPlayer and wrap the load in createAudioPlayer():
import { FancyError } from './../lib/FancyError';
// …
if (!audioBuffer) {
// Load and decode audio file
const assetsPath = this.engine.setting('AssetsPath') as Record<string, string>;
const url = `${assetsPath.root}/${assetsPath[this.directory]}/${this.media}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
audioBuffer = await audioContext.decodeAudioData(await response.arrayBuffer());
} catch (error) {
FancyError.show('action:play:load_failed', {
type: this.type,
media: this.mediaKey,
url,
reason: error instanceof Error ? error.message : String(error),
statement: `<code class='language=javascript'>"${this._statement}"</code>`,
label: this.engine.state('label'),
step: this.engine.state('step'),
});
throw error;
}
}In debug/index.js, inside registerErrors(), next to the Video action’s template:
// Play Action
FancyError.register('action:play:load_failed', {
title: 'The {{type}} "{{media}}" could not be loaded.',
message: 'Monogatari tried to load and decode the file {{url}} and failed.',
props: {
'File': '{{url}}',
'Reason': '{{reason}}',
'Statement': '{{statement}}',
'Label': '{{label}}',
'Step': '{{step}}',
'Help': {
'_': 'Check that the file exists in that folder and that its name matches the one in your assets. Audio only loads when the game is served, not opened from a file.',
},
},
});Rebuild both bundles, since the template lives in the debug module:
bunx tsc --noEmit
bun build.ts --browser
bun build.ts --debug
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/music-load-failed.spec.js'Rethrowing keeps today’s flow: run() rejects, didApply() never runs, so nothing reaches the state or the history. The dialog shows only with the debug module loaded, as every FancyError does (Errors and the Debug Module); a real change would also add the id to Diagnosing Errors.
Related pages
- Music, Sound and Voice: the same features from a game developer’s side.
- Play Music, Play Sound, Play Voice, Stop Music, Pause, Preload, Unload and Show Video: the statements, word by word.
- Show Scene, Show Background, Show Image, Characters and Character Layers: the visual statements.
- Configuration:
AssetsPath,Preload,ServiceWorkers,MainScreenMusicand the volume preferences. - Loading Screen and Settings Screen: the components that show preload progress and the volume sliders.
- What works opened from a file and Releasing on the Web: why a served game behaves differently.
- State, Storage and Rollback and Saving and Loading: what the media actions record and how it is replayed.
- Statements and Actions:
prepareAction(),run()and theshouldProceed()vetoes these actions take part in. - Testing: running Cypress against
dist/index.html.