All files / src sample-player.js

83.87% Statements 52/62
95.45% Branches 21/22
68.75% Functions 11/16
83.01% Lines 44/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114                      37x 37x 37x 37x 37x 37x   37x                                                           9x 9x                   258x 224x 224x 224x 224x 201x 201x 201x 201x 201x 201x 201x 201x   224x 224x 2x 2x   224x 202x 224x 224x               3x 2x 2x 2x 2x 2x 2x 1x 1x   2x 2x 2x         1x       1x      
import { loadData } from "./loader.js";
 
/**
 * Base class for audio components that load and play back sample buffers
 * (e.g. disc drive noise, cassette relay clicks).
 *
 * Provides: gain node setup, sample loading, one-shot playback, and
 * gain-based mute/unmute.  Subclasses add domain-specific behaviour.
 */
export class SamplePlayer {
    constructor(context, destination, volume) {
        this.context = context;
        this.volume = volume;
        this.sounds = {};
        this.gain = context.createGain();
        this.gain.gain.value = volume;
        this.gain.connect(destination);
        // Prevent older Safari from GC-ing in-flight AudioBufferSourceNodes.
        this.playing = [];
    }
 
    /**
     * Load a map of {name: path} into decoded AudioBuffers stored in this.sounds.
     */
    async loadSounds(pathMap) {
        const entries = Object.entries(pathMap);
        const decoded = await Promise.all(
            entries.map(async ([, path]) => {
                const data = await loadData(path);
                // Safari doesn't support the promise form of decodeAudioData.
                return new Promise((resolve, reject) => {
                    this.context.decodeAudioData(
                        data.buffer,
                        (buf) => resolve(buf),
                        (err) => reject(err),
                    );
                });
            }),
        );
        for (let i = 0; i < entries.length; i++) {
            this.sounds[entries[i][0]] = decoded[i];
        }
    }
 
    /**
     * Fire-and-forget: play a buffer once, return its duration.
     */
    oneShot(sound) {
        this.startSound(sound);
        return sound.duration;
    }
 
    /**
     * Start `sound` at `when` on the audio clock (now if 0), `offset` seconds in, for
     * `duration` seconds (the rest of it if undefined), with `fadeSeconds` of fade at each
     * end so a cut into the middle of it does not click. Returns the source, or null when
     * the context is not running.
     */
    startSound(sound, { when = 0, offset = 0, duration, fadeSeconds = 0 } = {}) {
        if (this.context.state !== "running") return null;
        const source = this.context.createBufferSource();
        source.buffer = sound;
        let into = this.gain;
        if (fadeSeconds > 0 && duration !== undefined) {
            const fade = this.context.createGain();
            const start = when || this.context.currentTime;
            fade.gain.setValueAtTime(0, start);
            fade.gain.linearRampToValueAtTime(1, start + fadeSeconds);
            fade.gain.setValueAtTime(1, start + duration - fadeSeconds);
            fade.gain.linearRampToValueAtTime(0, start + duration);
            fade.connect(this.gain);
            into = fade;
        }
        source.connect(into);
        source.onended = () => {
            this.playing = this.playing.filter((s) => s !== source);
            if (into !== this.gain) into.disconnect();
        };
        if (duration === undefined) source.start(when, offset);
        else source.start(when, offset, duration);
        this.playing.push(source);
        return source;
    }
 
    /**
     * Play a buffer, optionally looping.  Returns a Promise that resolves
     * with the source node (if looping) or when playback ends (if not).
     */
    play(sound, loop) {
        if (this.context.state !== "running") return Promise.reject();
        return new Promise((resolve) => {
            const source = this.context.createBufferSource();
            source.loop = !!loop;
            source.buffer = sound;
            source.connect(this.gain);
            source.onended = () => {
                this.playing = this.playing.filter((s) => s !== source);
                Eif (!source.loop) resolve();
            };
            source.start();
            this.playing.push(source);
            if (source.loop) resolve(source);
        });
    }
 
    mute() {
        this.gain.gain.value = 0;
    }
 
    unmute() {
        this.gain.gain.value = this.volume;
    }
}