registry_sound_sound_registry.js

/**
 * @module SoundRegistry
 * @fileoverview Contains SoundRegistry class.
 */

import SoundResources from "./sound_resources.js";

/**
 * Loads audio from files and allow for easily and ready access.
 * @class
 */
class SoundRegistry {
    /**
     * Create a new sound loader.
     * @constructor
     */
    constructor() {
        this._sounds = new Map();
        this._pools = new Map();

        this._wp = "";
    }


    //
    // Loading
    //

    /**
     * Set the working directory for importing sprites.
     * @param {string} p New working path
     */
    path(p) {
        const l = p.length - 1;
        if (p[l] !== '/' && p[l] !== '\\')
            p = p + "/";

        this._wp = p;
    }

    /**
     * Load a sound from files.
     * @param {string} id ID/name of sound for later access
     * @param {string} path Path to file
     */
    load(id, path) {
        $$.loadInc();

        const audio = new Audio(this._wp + path);
        audio.addEventListener("loadeddata", () => {
            this._sounds.set(id, audio);
            this._pools.set(id, []);
            $$.loadDec();
        });

        audio.load();
    }


    //
    // Access
    //

    getInstance(id) {
        if (this._pools.get(id).length === 0)
            return new SoundResources(this._sounds.get(id).cloneNode());

        return this._pools.get(id).pop();
    }

    releaseInstance(id, instance) {
        this._pools.get(id).push(instance);
    }

    /**
     * Get a sound based on its ID, if it has been loaded.
     * @param {string} id Identifier of sound to get
     * @returns {Audio|null} Audio with specified identifier, if it exists
     */
    get(id) {
        if (!this._sounds.has(id))
            return null;

        return this._sounds.get(id).cloneNode();
    }
}

export default SoundRegistry;