All files / src/digital audio.ts

0% Statements 0/121
0% Branches 0/59
0% Functions 0/39
0% Lines 0/120

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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { TimeInSeconds } from "../midi/types";

declare var window: any;

function log10(x: number) {
  return Math.log(x) / Math.LN10;
}
 
export interface IAndySoundNode {
  readonly node?: AudioNode;
  readonly nodeInput?: AudioNode;
}
 
/*
  +-------------------+
  | IAndySoundNode    |
  | i - nodeInput     |
  | o - node          |
  +-------------------+
 
  +---------------------+
  | Sound               |
  | i - source (buffer) |
  | - volume (gain)     |
  | - panner (panner)   |
  | o - panner          |
  +---------------------+
 
  +--------------------+
  | SoundSystem        |
  | i - masterGainNode |
  | - analyser         |
  | o - speakers       |
  +--------------------+
  | play(Sound)        |
  +--------------------+
*/
 
/**
 * Sound represents a single sound file. For example an mp3, or ogg.
 * (Use the loadSound function to fetch a file). After you have a 
 * Sound you can use the play() method on the SoundSystem to play
 * the sound.
 */
export class Sound implements IAndySoundNode {
  public buffer: AudioBuffer;
 
  public loop: boolean;
  /** if looping where to start the loop (in seconds) */
  public loopStart: number;
  /** if looping where to end the loop (in seconds) */
  public loopEnd: number;
 
  public isInContext = false;
  // True if the sound is currently playing
  public isPlaying = false;
  // public isMusic = false;

  constructor(buffer: AudioBuffer) {
    this.buffer = buffer;
    this.loop = false;
    this.loopStart = 0;
    this.loopEnd = this.buffer.length;
  }

  private source: AudioBufferSourceNode | undefined;
  public volume: GainNode | undefined;
  public panner: PannerNode | undefined;

  setContext(context: AudioContext) {
    this.volume = context.createGain();
    // Note: we start with our volume all the way down
    // you need to set it to something by default
    this.volume.gain.setValueAtTime(0.0000001, 0);

    // TODO: the panner should be on a "track"
    this.panner = context.createPanner();
    this.panner.panningModel = 'HRTF';
    this.panner.distanceModel = 'inverse';
    this.panner.refDistance = 1;
    this.panner.maxDistance = 1000;
    this.panner.rolloffFactor = 1;
    this.panner.coneInnerAngle = 360;
    this.panner.coneOuterAngle = 0;
    this.panner.coneOuterGain = 0;
    // orientation looking down the z axis
    this.panner.orientationX.setValueAtTime(0, 0);
    this.panner.orientationY.setValueAtTime(0, 0);
    this.panner.orientationZ.setValueAtTime(-1, 0);
    this.panner.positionX.setValueAtTime(0, 0);
    this.panner.positionY.setValueAtTime(0, 0);
    this.panner.positionZ.setValueAtTime(0, 0);
    //////

    this.source = context.createBufferSource();

    this.source.onended = () => {
      this.isPlaying = false;
    }

    this.source.connect(this.volume);
    this.volume.connect(this.panner);
 
    this.source.buffer = this.buffer;
    this.source.loop = this.loop;
    this.isInContext = true;
  }

  get nodeInput(): AudioNode | undefined {
    return this.source;
  }

  get node(): AudioNode | undefined {
    // return (this.isMusic) ? this.volume : this.panner;
    // return this.volume;
    return this.panner;
  }
 
  play(time: number = 0) {
    if (!this.isInContext) {
      throw new Error('Sound not in context');
    }
 
    if (this.source && this.loop) {
      this.source.loop = this.loop;
      this.source.loopStart = this.loopStart;
      this.source.loopEnd = this.loopEnd;
      this.source.start(time);
    } else if (this.source) {
      this.source.loop = false;
      this.source.start(time);
    }
  }

  stop() {
    if (this.source)
      this.source.stop();
  }

  destroy() {
    this.source?.stop();
    if (this.volume)
      this.source?.disconnect(this.volume);
    if (this.panner)
      this.volume?.disconnect(this.panner);
  }
}

/**
 * This is the main crux of Andy. It sets up a bunch of default audio
 * nodes so you can control volume and panning and such and you can 
 * send it Sound files via play() to play sounds.
 */
export class SoundSystem implements IAndySoundNode {
  static addSoundToContext(context: AudioContext, sound: Sound) {
    sound.setContext(context);
  }
  static soundContext: AudioContext;
  static masterGainNode: GainNode;
  static analyser: AnalyserNode;
 
  constructor() {
    this.reboot();
  }
 
  context() {
    return SoundSystem.soundContext;
  }
 
  masterGainNode() {
    return SoundSystem.masterGainNode;
  }
 
  get nodeInput(): AudioNode | undefined {
    return this.masterGainNode();
  }

  reboot() {
    try {
      const AudioContext = window.webkitAudioContext // Safari and old versions of Chrome
        || window.AudioContext                       // Default
        || false;

      if (AudioContext) {
        if (SoundSystem.soundContext) {
          SoundSystem.soundContext.suspend();
        }
        SoundSystem.soundContext = new AudioContext();
 
        SoundSystem.soundContext.onstatechange = this.handleStateChange;
 
        SoundSystem.soundContext.audioWorklet.addModule('noise.processor.js');
 
        SoundSystem.analyser = SoundSystem.soundContext.createAnalyser();
 
        SoundSystem.masterGainNode = SoundSystem.soundContext.createGain();
        SoundSystem.masterGainNode.gain.value = 1;

        SoundSystem.masterGainNode.connect(SoundSystem.soundContext.destination);
 
        SoundSystem.masterGainNode.connect(SoundSystem.analyser);

        window.addEventListener('focus', (event: any) => this.resumePlay());
      } else {
        console.error('Andy: Web Audio API is not supported in this browser');
      }
    } catch (e) {
      console.error('Andy: Error creating Web Audio context', e);
    }
  }

  public getAnalyser(): AnalyserNode {
    return SoundSystem.analyser;
  }
 
  /** Get the current volume setting: 0 - 1 */
  public volume(): number {
    return SoundSystem.masterGainNode.gain.value;
  }

  /**
   * Gets the current volume setting in decibels
   */
  public volumeInDB(): number {
    return 20 * log10(this.volume());
  }

  /**
   * Sets the current volume using decibels
   */
  public setVolumeInDB(decibel: number) {
    this.adjustVolume(Math.pow(10, (decibel / 20)));
  }

  /** Set the current volume to: 0 - 1 */
  public adjustVolume(by: number) {
    SoundSystem.masterGainNode.gain.value = by;
  }

  /** Play the given sound in the system. Note the sound does not
   * have to be connected to anything, this will connect the sound 
   * to the master gain node before playing.
   * 
   * Time is an offset within the sound to play from. e.g. 0 is from
   * the start of the sample.
   */
  public play(sound: Sound, multiple = false, time: TimeInSeconds = 0) {
    if (multiple === true || !sound.isPlaying) {
      this.playSound(sound, time);
    }
  }
 
  public stop(sound: Sound) {
    if (sound.isPlaying) {
      sound.stop();
      sound.isPlaying = false;
    }
  }
 
  /** Get the sound contexts precise current time 
   * (ever-increasing hardware timestamp in seconds) */
  public currentTime(): TimeInSeconds {
    if (!SoundSystem.soundContext) {
      return 0;
    }
    return SoundSystem.soundContext.currentTime;
  }
 
  /**
   * Given an array buffer of wav, mp3, ogg, etc try to turn it
   * into an audio buffer we can play. 
   */
  public decodeSound(data: ArrayBuffer): Promise<AudioBuffer> {
    return new Promise<AudioBuffer>((res, rej) => {
      let buffer: AudioBuffer;
      if (SoundSystem.soundContext) {
        SoundSystem.soundContext.decodeAudioData(data, (ab: AudioBuffer) => {
          buffer = ab;
          res(buffer);
        },
          (error: any) => {
            console.error(error);
            rej(error);
          }
        );
      }
    });
  }
 
  public resumePlay(): Promise<void> {
    return SoundSystem.soundContext.resume();
  }
 
  private playSound(sound: Sound, time: TimeInSeconds = 0) {
    // Put the sound into our current context
    sound.setContext(this.context());
    // connect to current master gain node
    if (sound.node) {
      sound.node.connect(this.masterGainNode());
    }
    // default
    sound.volume?.gain.setValueAtTime(0.8, time);
    sound.play(time);
    sound.isPlaying = true;
  }
 
  private handleStateChange(e: Event): any {
    if (SoundSystem.soundContext && SoundSystem.soundContext.state !== 'running') {
      this.resumePlay();
    }
    return undefined;
  }
}
 
/**
 * Load a sound from the server, and pass it through the 
 * sound system to try to decode the file into mp3, etc
 */
export const loadSound = (url: string, soundSystem: SoundSystem): Promise<Sound> => {
  return new Promise((resolve, reject) => {
    const headers = new Headers();
    headers.append('User-Agent', 'Andy/1.0');
    // if (mimeType) {
    //   headers.append('Accept', mimeType);
    //   headers.append('Content-Type', mimeType);
    // }
    const body = undefined;
    fetch(url, {
      method: 'GET',
      mode: 'cors',
      cache: 'reload',
      headers: headers,
      credentials: 'same-origin',
      redirect: 'follow',
      referrerPolicy: 'no-referrer',
      body: (body) ? JSON.stringify(body) : body,
    })
      .then(response => response.arrayBuffer())
      .then(response => {
        soundSystem.decodeSound(<ArrayBuffer>response).then(
          (b: AudioBuffer) => {
            const sound = new Sound(b);
            resolve(sound);
          },
          (err) => {
            reject(err);
          }).catch(e => console.error(e));
      }).catch(e => console.error(e));
  });
};