Assets and Audio
An asset is a file your game shows or plays: a scene’s picture, a song, a video. You register each one under a short name, and the script uses the name (show scene forest, play music theme). This page lists the methods that hold the names, load the files before they’re needed, keep loaded files in memory, and reach the players that are playing.
Served, the engine reads each audio file’s data and plays it through Web Audio. Opened from a file, a browser refuses to let the page read it, so the engine plays it through an <audio> element instead, without the audio effects. See What works opened from a file.
Register and read assets
The files live in the assets folder, one folder per category. The AssetsPath setting names the folders:
| Category | Folder | Used by |
|---|---|---|
scenes |
assets/scenes |
show scene |
images |
assets/images |
show image |
music |
assets/music |
play music |
sounds |
assets/sounds |
play sound |
voices |
assets/voices |
play voice |
videos |
assets/videos |
show video |
gallery |
assets/gallery |
The gallery screen |
Characters’ pictures are in assets/characters, named in each character’s own properties rather than with assets().
assets()
Reads the registered assets, or adds some to a category.
assets(): object
assets(category: string): object | undefined
assets(category: string, object: object): void| Form | What it does |
|---|---|
assets() |
Returns every category, each an object of names and files. |
assets('scenes') |
Returns one category. |
assets('scenes', { … }) |
Adds the names and files to a category, keeping the ones it had. A category that doesn’t exist is created. |
The starter game’s js/script.js has a call for each category:
monogatari.assets('scenes', {
'hall': 'hall.png',
});
monogatari.assets('music', {
'theme': 'theme.ogg',
});The file names are relative to the category’s folder: hall.png is assets/scenes/hall.png.
A category of your own (assets('maps', { … })) needs a folder in the AssetsPath setting too, such as monogatari.settings({ 'AssetsPath': { 'maps': 'maps' } }). The preloading looks for its files there, and without one, each of them fails to load.
asset()
Reads or changes one asset.
asset(category: string, name: string, file?: string | null): string | undefinedmonogatari.asset('scenes', 'hall'); // 'hall.png'
monogatari.asset('scenes', 'roof', 'roof.png'); // adds it, returns 'roof.png'It returns the file, or undefined for a name the category doesn’t have. A category that doesn’t exist prints Tried to interact with a non-existing asset type … on the console and throws an error.
Preload
preload()
Loads the game’s files while the loading screen shows, so they’re ready when the script needs them. init() calls it; a game doesn’t need to.
preload(): Promise<void>It does nothing (and resolves at once) when the Preload setting is false, in the desktop app, in a Cordova app, and in a game opened from a file. Otherwise it works one of two ways:
- Without a
defaultpreload block (the starter game): it downloads every file of every category, and every character’s pictures, so the browser has them in its cache. A file declared twice is downloaded once. The engine doesn’t keep them itself. - With a
defaultblock (monogatari.action('Preload').blocks({ default: { … } })): it loads only the files the block lists, into the engine’s caches, ready to show and play at once. Preload describes the blocks.
It fires willPreloadAssets, then assetQueued for each file it starts, assetLoaded or assetFailed as each one finishes, and didPreloadAssets when they all have (see Events). The loading screen moves its bar with them.
A file that fails to load (a typo in its name, a missing file) doesn’t stop the others. Its error goes to the console, assetFailed fires for it, and the promise still resolves once every file has finished. With the debug file loaded, an error dialog then lists the files that failed (Some of your game’s files could not be preloaded). The game goes on to the main menu, and asks for each failed file again when the story uses it. Before 2.9.0, one failed file made the promise reject and didPreloadAssets never fired.
The caches
The engine keeps loaded images and decoded audio in memory, so showing or playing them again needs no new download. The preload statement and a default preload block fill the caches; unload empties them; show scene, show image, show character and play use what they find. A key is the category and the name, scenes/hall or music/theme; a character’s picture is characters/<character>/<sprite>.
| Method | What it does |
|---|---|
imageCache(key) |
Returns the cached <img> element, or undefined. |
imageCache(key, image) |
Caches an <img> element. |
imageUncache(key) |
Removes one image. Returns true if it was there. |
imageClearCache(prefix?) |
Removes every image, or the ones whose key starts with prefix ('scenes/'). |
audioBufferCache(key) |
Returns the cached AudioBuffer, or undefined. |
audioBufferCache(key, buffer) |
Caches an AudioBuffer. |
audioBufferUncache(key) |
Removes one. Returns true if it was there. |
audioBufferClearCache(prefix?) |
Removes every one, or the ones whose key starts with prefix. |
clearAllCaches() |
Empties both caches. |
Decoded audio between sessions
Decoding a song takes time, so the preload statement also keeps the decoded audio in an IndexedDB database named after the game with _AudioCache added. The next time the player opens the game, the audio comes from there, without downloading or decoding. These methods reach that database; the keys are the files’ addresses (assets/music/theme.ogg).
| Method | What it does |
|---|---|
audioBufferSpace() |
Resolves with the database, or null when the browser has no IndexedDB. |
isIndexedDBAvailable() |
true or false once the engine has tried to open one of its IndexedDB databases, null before. |
storeAudioBufferPersistent(key, buffer) |
Stores an AudioBuffer. Resolves when done; a failure only prints a warning. |
getAudioBufferPersistent(key) |
Resolves with the AudioBuffer, or undefined. Needs audioContext. |
removeAudioBufferPersistent(key) |
Removes one. |
clearAudioBufferPersistent() |
Removes every one. |
serializeAudioBuffer(buffer) |
Turns an AudioBuffer into plain data: { channels, sampleRate, length, numberOfChannels }. |
deserializeAudioBuffer(data, audioContext) |
Turns that data back into an AudioBuffer. |
The service worker’s cache
When the game is served and the ServiceWorkers setting is on, the starter game’s service-worker.js keeps the files the game downloads, so it loads faster and can run offline. These methods ask it about its cache:
| Method | What it resolves with |
|---|---|
cacheInServiceWorker(urls) |
{ success, cached, total }: asks the worker to download and keep each address in the array. cached counts the ones that worked. |
isInServiceWorkerCache(url) |
true when the worker has the address. |
getFromServiceWorkerCache(url) |
The file’s data as an ArrayBuffer, or undefined. |
They need a service worker in control of the page. The starter game’s worker takes control a moment after the game first loads. Before that, in a game opened from a file, with the ServiceWorkers setting off, or after 10 seconds without an answer, they resolve with { success: false, error }, false and undefined.
Media players
While music, a sound, a voice line or a video plays, the engine keeps its player under its type and name. Music, sound and voice play through Web Audio, with a Monogatari.AudioPlayer; a video is a <video> element.
mediaPlayers()
Returns the players.
mediaPlayers(): object
mediaPlayers(type: string): array
mediaPlayers(type: string, asObject: true): object| Form | What it returns |
|---|---|
mediaPlayers() |
{ music, sound, voice, video }, each an object of players by name. |
mediaPlayers('music') |
The music players, as an array. |
mediaPlayers('music', true) |
The music players, as an object by name. |
mediaPlayer()
Returns one player, or stores one.
mediaPlayer(type: string, name: string): AudioPlayer | HTMLVideoElement | undefined
mediaPlayer(type: string, name: string, player: AudioPlayer | HTMLMediaElement): AudioPlayer | HTMLMediaElementAn AudioPlayer has play(), pause() and stop(), fadeIn(seconds, volume) and fadeOut(seconds), and the properties volume (0 to 1), loop, paused, isPlaying, ended, duration and currentTime (in seconds). In a game opened from a file, or for a track the browser didn’t let the game read, the player plays through an <audio> element: it’s still an AudioPlayer, with the same methods and properties, and it applies no effects.
const theme = monogatari.mediaPlayer('music', 'theme');
if (theme) {
theme.volume = 0.3;
}The music plays on, quieter. The next play music statement, or a change of the volume preference, sets the volume again.
removeMediaPlayer()
Stops a player and forgets it, or every player of a type. An <audio> or <video> element you registered with mediaPlayer() is paused and emptied, without firing an error event.
removeMediaPlayer(type: string, name?: string): voidIt doesn’t change the state: the music list still names the song, so a save or a rollback brings it back. To stop music for good, run the statement: monogatari.run('stop music theme', false).
audioContext
The Web Audio AudioContext the audio plays through, created while init() runs.
audioContext: AudioContext | undefined;The main menu’s music
The MainScreenMusic setting names a music asset that plays while the main menu shows. It doesn’t use the media players.
ambientPlayer
The <audio> element that plays it, created by init().
ambientPlayer: HTMLAudioElement | null;playAmbient()
Plays the MainScreenMusic song, in a loop, at the player’s music volume. The main screen calls it when it opens.
playAmbient(): voidIt does nothing when MainScreenMusic is empty or the song already plays. A name that isn’t a music asset opens an error dialog. Browsers don’t let a page play sound before the player has clicked or pressed a key in it: when the browser refuses, the engine shows a banner, “Click here to allow audio playback”, and plays the song once the player clicks it.
stopAmbient()
Pauses the main menu’s song. The main screen calls it when it closes because a game starts or loads, and the jump statement calls it.
stopAmbient(): void