Audiosynth => ES6

by stevenkaspar

JavaScript

class SynthInstrument {
  constructor(_parent, name, _soundID){
    this._parent  = _parent;
    this.name     = name;
    this._soundID = _soundID;
  }
	playKey(key, duration){
  	var split  = key.split('/');
    var note   = split[0];
    var octave = parseInt(split[1]);
    
    this.play(note, octave, duration);
  }
  play(note, octave, duration){
    return this._parent.play(this._soundID, note, octave, duration);
  }

  generate(note, octave, duration){
    return this._parent.generate(this._soundID, note, octave, duration);
  }
}

class Synth {

  constructor(){
  

    this.URL                = window.URL || window.webkitURL;
    this.Blob               = window.Blob;
    this._encapsulated      = false;
    this._bitsPerSample     = 16;
    this._channels          = 1;
    this._sampleRate        = 44100;
    this._volume            = 32768;
    this._notes = {
      'C': 261.63,
      'C#': 277.18,
      'D': 293.66,
      'D#': 311.13,
      'E': 329.63,
      'F': 346.23,
      'F#': 369.99,
      'G': 392.00,
      'G#': 415.30,
      'A': 440.00,
      'A#': 466.16,
      'B': 493.88
    }
    this._fileCache = [];
    this._temp      = {};
    this._sounds    = [];
    this._mod = [(i, s, f, x) => {
      return Math.sin((2 * Math.PI) * (i / s) * f + x);
    }];
    this.profiles = [{
      name: 'piano',
      attack: () => {
        return 0.002;
      },
      dampen: (sampleRate, frequency, volume) => {
        return Math.pow(0.5 * Math.log((frequency * volume) / sampleRate), 2);
      },
      wave: (i, sampleRate, frequency, volume) => {
        var base = this._mod[0];
        return this._mod[1](
          i,
          sampleRate,
          frequency,
          Math.pow(base(i, sampleRate, frequency, 0), 2) +
          (0.75 * base(i, sampleRate, frequency, 0.25)) +
          (0.1 * base(i, sampleRate, frequency, 0.5))
        );
      }
    }];
    
    if (!this.URL || !this.Blob) {
      throw new Error('This browser does not support...