diff --git a/changelog.md b/changelog.md
index 10d0394d..a3e11e18 100644
--- a/changelog.md
+++ b/changelog.md
@@ -1,3 +1,9 @@
+p5.sound v. 0.3.8
+- many updates to documentation and examples
+- protect against errors during duplicate dispose/disconnect calls to ensure dispose methods free up resources, and to enable testing in headless Chrome
+- Deprecate p5.Env in favor of p5.Envelope
+- p5.MonoSynth and p5.PolySynth updates and bug fixes
+
p5.sound v. 0.3.7
- fix audioIn getSources
- improvements to soundFile.rate
diff --git a/lib/p5.sound.js b/lib/p5.sound.js
index c68ee25f..5bb703c7 100644
--- a/lib/p5.sound.js
+++ b/lib/p5.sound.js
@@ -1,4 +1,4 @@
-/*! p5.sound.js v0.3.7 2018-01-19 */
+/*! p5.sound.js v0.3.8 2018-06-15 */
/**
* p5.sound extends p5 with Web Audio functionality including audio input,
@@ -73,9 +73,11 @@
factory(root['p5']);
}(this, function (p5) {
-var sndcore;
-'use strict';
-sndcore = function () {
+var shims;
+'use strict'; /**
+ * This module has shims
+ */
+shims = function () {
/* AudioContext Monkeypatch
Copyright 2013 Chris Wilson
Licensed under the Apache License, Version 2.0 (the "License");
@@ -207,20 +209,6 @@ sndcore = function () {
}
}(window));
// <-- end MonkeyPatch.
- // Create the Audio Context
- var audiocontext = new window.AudioContext();
- /**
- *
Returns the Audio Context for this sketch. Useful for users
- * who would like to dig deeper into the Web Audio API
- * .
- *
- * @method getAudioContext
- * @return {Object} AudioContext for this sketch
- */
- p5.prototype.getAudioContext = function () {
- return audiocontext;
- };
// Polyfill for AudioIn, also handled by p5.dom createCapture
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
/**
@@ -265,6 +253,49 @@ sndcore = function () {
return false;
}
};
+}();
+var audiocontext;
+'use strict';
+audiocontext = function () {
+ // Create the Audio Context
+ var audiocontext = new window.AudioContext();
+ /**
+ * Returns the Audio Context for this sketch. Useful for users
+ * who would like to dig deeper into the Web Audio API
+ * .
+ *
+ * Some browsers require users to startAudioContext
+ * with a user gesture, such as touchStarted in the example below.
+ *
+ * @method getAudioContext
+ * @return {Object} AudioContext for this sketch
+ * @example
+ *
+ * function draw() {
+ * background(255);
+ * textAlign(CENTER);
+ *
+ * if (getAudioContext().state !== 'running') {
+ * text('click to start audio', width/2, height/2);
+ * } else {
+ * text('audio is enabled', width/2, height/2);
+ * }
+ * }
+ *
+ * function touchStarted() {
+ * if (getAudioContext().state !== 'running') {
+ * getAudioContext().resume();
+ * }
+ * var synth = new p5.MonoSynth();
+ * synth.play('A4', 0.5, 0, 0.2);
+ * }
+ *
+ *
+ */
+ p5.prototype.getAudioContext = function () {
+ return audiocontext;
+ };
// if it is iOS, we have to have a user interaction to start Web Audio
// http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false;
@@ -289,6 +320,7 @@ sndcore = function () {
document.addEventListener('touchend', startIOS, false);
document.addEventListener('touchstart', startIOS, false);
}
+ return audiocontext;
}();
var master;
'use strict';
@@ -343,7 +375,7 @@ master = function () {
* 1.0 is the maximum amplitude of a digital sound, so multiplying
* by greater than 1.0 may cause digital distortion. To
* fade, provide a rampTime
parameter. For more
- * complex fades, see the Env class.
+ * complex fades, see the Envelope class.
*
* Alternately, you can pass in a signal source such as an
* oscillator to modulate the amplitude with an audio signal.
@@ -464,9 +496,38 @@ helpers = function () {
* }
*
*/
- p5.prototype.midiToFreq = function (m) {
+ var midiToFreq = p5.prototype.midiToFreq = function (m) {
return 440 * Math.pow(2, (m - 69) / 12);
};
+ // This method converts ANSI notes specified as a string "C4", "Eb3" to a frequency
+ noteToFreq = function (note) {
+ if (typeof note !== 'string') {
+ return note;
+ }
+ var wholeNotes = {
+ A: 21,
+ B: 23,
+ C: 24,
+ D: 26,
+ E: 28,
+ F: 29,
+ G: 31
+ };
+ var value = wholeNotes[note[0].toUpperCase()];
+ var octave = ~~note.slice(-1);
+ value += 12 * (octave - 1);
+ switch (note[1]) {
+ case '#':
+ value += 1;
+ break;
+ case 'b':
+ value -= 1;
+ break;
+ default:
+ break;
+ }
+ return midiToFreq(value);
+ };
/**
* List the SoundFile formats that you will include. LoadSound
* will search your directory for these extensions, and will pick
@@ -581,7 +642,7 @@ helpers = function () {
return path;
};
/**
- * Used by Osc and Env to chain signal math
+ * Used by Osc and Envelope to chain signal math
*/
p5.prototype._mathChain = function (o, math, thisChain, nextChain, type) {
// if this type of math already exists in the chain, replace it
@@ -600,7 +661,10 @@ helpers = function () {
o.mathOps[thisChain] = math;
return o;
};
- return { midiToFreq: p5.prototype.midiToFreq };
+ return {
+ midiToFreq: midiToFreq,
+ noteToFreq: noteToFreq
+ };
}(master);
var errorHandler;
'use strict';
@@ -669,7 +733,9 @@ panner = function () {
this.stereoPanner.connect(obj);
};
p5.Panner.prototype.disconnect = function () {
- this.stereoPanner.disconnect();
+ if (this.stereoPanner) {
+ this.stereoPanner.disconnect();
+ }
};
} else {
// if there is no createStereoPanner object
@@ -726,7 +792,9 @@ panner = function () {
this.output.connect(obj);
};
p5.Panner.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
}
}(master);
@@ -896,7 +964,9 @@ soundfile = function () {
if (typeof callback === 'function') {
callback.apply(self, arguments);
}
- self._decrementPreload();
+ if (typeof self._decrementPreload === 'function') {
+ self._decrementPreload();
+ }
}, onerror, whileLoading);
return s;
};
@@ -1017,6 +1087,10 @@ soundfile = function () {
* @param {Number} [duration] (optional) duration of playback in seconds
*/
p5.SoundFile.prototype.play = function (startTime, rate, amp, _cueStart, duration) {
+ if (!this.output) {
+ console.warn('SoundFile.play() called after dispose');
+ return;
+ }
var self = this;
var now = p5sound.audiocontext.currentTime;
var cueStart, cueEnd;
@@ -1119,7 +1193,8 @@ soundfile = function () {
* @param {String} str 'restart' or 'sustain' or 'untilDone'
* @example
*
- * function setup(){
+ * var mySound;
+ * function preload(){
* mySound = loadSound('assets/Damscray_DancingTiger.mp3');
* }
* function mouseClicked() {
@@ -1329,7 +1404,7 @@ soundfile = function () {
* 1.0 is the maximum amplitude of a digital sound, so multiplying
* by greater than 1.0 may cause digital distortion. To
* fade, provide a rampTime
parameter. For more
- * complex fades, see the Env class.
+ * complex fades, see the Envelope class.
*
* Alternately, you can pass in a signal source such as an
* oscillator to modulate the amplitude with an audio signal.
@@ -1379,7 +1454,7 @@ soundfile = function () {
* var ball = {};
* var soundFile;
*
- * function setup() {
+ * function preload() {
* soundFormats('ogg', 'mp3');
* soundFile = loadSound('assets/beatbox.mp3');
* }
@@ -1736,7 +1811,9 @@ soundfile = function () {
* @method disconnect
*/
p5.SoundFile.prototype.disconnect = function () {
- this.panner.disconnect();
+ if (this.panner) {
+ this.panner.disconnect();
+ }
};
/**
*/
@@ -2057,6 +2134,11 @@ soundfile = function () {
* useful for removeCue(id)
* @example
*
+ * var mySound;
+ * function preload() {
+ * mySound = loadSound('assets/beat.mp3');
+ * }
+ *
* function setup() {
* background(0);
* noStroke();
@@ -2064,8 +2146,6 @@ soundfile = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * mySound = loadSound('assets/beat.mp3');
- *
* // schedule calls to changeText
* mySound.addCue(0.50, changeText, "hello" );
* mySound.addCue(1.00, changeText, "p5" );
@@ -2146,7 +2226,7 @@ soundfile = function () {
}
this._prevTime = playbackTime;
};
-}(sndcore, errorHandler, master, helpers);
+}(errorHandler, master, helpers);
var amplitude;
'use strict';
amplitude = function () {
@@ -2295,7 +2375,9 @@ amplitude = function () {
}
};
p5.Amplitude.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
// TO DO make this stereo / dependent on # of audio channels
p5.Amplitude.prototype._audioProcess = function (event) {
@@ -2413,10 +2495,15 @@ amplitude = function () {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
- this.input.disconnect();
- this.output.disconnect();
- this.input = this.processor = undefined;
- this.output = undefined;
+ if (this.input) {
+ this.input.disconnect();
+ delete this.input;
+ }
+ if (this.output) {
+ this.output.disconnect();
+ delete this.output;
+ }
+ delete this.processor;
};
}(master);
var fft;
@@ -2817,7 +2904,7 @@ fft = function () {
*
*
*function setup(){
- * cnv = createCanvas(800,400);
+ * cnv = createCanvas(100,100);
* sound = new p5.AudioIn();
* sound.start();
* fft = new p5.FFT();
@@ -2837,7 +2924,6 @@ fft = function () {
* fill(0,255,0); // spectrum is green
*
* //draw the spectrum
- *
* for (var i = 0; i< spectrum.length; i++){
* var x = map(log(i), 0, log(spectrum.length), 0, width);
* var h = map(spectrum[i], 0, 255, 0, height);
@@ -2861,8 +2947,8 @@ fft = function () {
* rect(centroidplot, 0, width / spectrum.length, height)
* noStroke();
* fill(255,255,255); // text is white
- * textSize(40);
- * text("centroid: "+round(spectralCentroid)+" Hz", 10, 40);
+ * text("centroid: ", 10, 20);
+ * text(round(spectralCentroid)+" Hz", 10, 40);
*}
*
*/
@@ -2898,8 +2984,10 @@ fft = function () {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
- this.analyser.disconnect();
- this.analyser = undefined;
+ if (this.analyser) {
+ this.analyser.disconnect();
+ delete this.analyser;
+ }
};
/**
* Returns an array of average amplitude values for a given number
@@ -5087,7 +5175,7 @@ oscillator = function () {
// set old osc free to be garbage collected (memory)
if (this.oscillator) {
this.oscillator.disconnect();
- this.oscillator = undefined;
+ delete this.oscillator;
}
// var detune = this.oscillator.frequency.value;
this.oscillator = p5sound.audiocontext.createOscillator();
@@ -5252,9 +5340,15 @@ oscillator = function () {
* @method disconnect
*/
p5.Oscillator.prototype.disconnect = function () {
- this.output.disconnect();
- this.panner.disconnect();
- this.output.connect(this.panner);
+ if (this.output) {
+ this.output.disconnect();
+ }
+ if (this.panner) {
+ this.panner.disconnect();
+ if (this.output) {
+ this.output.connect(this.panner);
+ }
+ }
this.oscMods = [];
};
/**
@@ -5904,9 +5998,9 @@ Tone_signal_TimelineSignal = function (Tone) {
};
return Tone.TimelineSignal;
}(Tone_core_Tone, Tone_signal_Signal);
-var env;
+var envelope;
'use strict';
-env = function () {
+envelope = function () {
var p5sound = master;
var Add = Tone_signal_Add;
var Mult = Tone_signal_Multiply;
@@ -5920,16 +6014,16 @@ env = function () {
* of an object, a series of fades referred to as Attack, Decay,
* Sustain and Release (
* ADSR
- * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Env can
+ * ). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can
* control an Oscillator's frequency like this: osc.freq(env)
.
- * Use setRange
to change the attack/release level.
- * Use setADSR
to change attackTime, decayTime, sustainPercent and releaseTime.
- * Use the play
method to play the entire envelope,
- * the ramp
method for a pingable trigger,
- * or triggerAttack
/
- * triggerRelease
to trigger noteOn/noteOff.
- *
- * @class p5.Env
+ * Use setRange
to change the attack/release level.
+ * Use setADSR
to change attackTime, decayTime, sustainPercent and releaseTime.
+ * Use the play
method to play the entire envelope,
+ * the ramp
method for a pingable trigger,
+ * or triggerAttack
/
+ * triggerRelease
to trigger noteOn/noteOff.
+ *
+ * @class p5.Envelope
* @constructor
* @example
*
@@ -5949,7 +6043,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -5966,7 +6060,7 @@ env = function () {
* }
*
*/
- p5.Env = function (t1, l1, t2, l2, t3, l3) {
+ p5.Envelope = function (t1, l1, t2, l2, t3, l3) {
/**
* Time until envelope reaches attackLevel
* @property attackTime
@@ -6021,7 +6115,7 @@ env = function () {
};
// this init function just smooths the starting value to zero and gives a start point for the timeline
// - it was necessary to remove glitches at the beginning.
- p5.Env.prototype._init = function () {
+ p5.Envelope.prototype._init = function () {
var now = p5sound.audiocontext.currentTime;
var t = now;
this.control.setTargetAtTime(0.00001, t, 0.001);
@@ -6048,7 +6142,7 @@ env = function () {
* var t2 = 0.3; // decay time in seconds
* var l2 = 0.1; // decay level 0.0 to 1.0
* var t3 = 0.2; // sustain time in seconds
- * var l3 = dL; // sustain level 0.0 to 1.0
+ * var l3 = 0.5; // sustain level 0.0 to 1.0
* // release level defaults to zero
*
* var env;
@@ -6061,7 +6155,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env(t1, l1, t2, l2, t3, l3);
+ * env = new p5.Envelope(t1, l1, t2, l2, t3, l3);
* triOsc = new p5.Oscillator('triangle');
* triOsc.amp(env); // give the env control of the triOsc's amp
* triOsc.start();
@@ -6077,7 +6171,7 @@ env = function () {
*
*
*/
- p5.Env.prototype.set = function (t1, l1, t2, l2, t3, l3) {
+ p5.Envelope.prototype.set = function (t1, l1, t2, l2, t3, l3) {
this.aTime = t1;
this.aLevel = l1;
this.dTime = t2 || 0;
@@ -6125,7 +6219,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -6142,7 +6236,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.setADSR = function (aTime, dTime, sPercent, rTime) {
+ p5.Envelope.prototype.setADSR = function (aTime, dTime, sPercent, rTime) {
this.aTime = aTime;
this.dTime = dTime || 0;
// lerp
@@ -6176,7 +6270,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -6193,7 +6287,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.setRange = function (aLevel, rLevel) {
+ p5.Envelope.prototype.setRange = function (aLevel, rLevel) {
this.aLevel = aLevel || 1;
this.rLevel = rLevel || 0;
};
@@ -6208,7 +6302,7 @@ env = function () {
// param {Number} attackTimeConstant attack time constant
// param {Number} decayTimeConstant decay time constant
//
- p5.Env.prototype._setRampAD = function (t1, t2) {
+ p5.Envelope.prototype._setRampAD = function (t1, t2) {
this._rampAttackTime = this.checkExpInput(t1);
this._rampDecayTime = this.checkExpInput(t2);
var TCDenominator = 1;
@@ -6219,7 +6313,7 @@ env = function () {
this._rampDecayTC = t2 / this.checkExpInput(TCDenominator);
};
// private method
- p5.Env.prototype.setRampPercentages = function (p1, p2) {
+ p5.Envelope.prototype.setRampPercentages = function (p1, p2) {
//set the percentages that the simple exponential ramps go to
this._rampHighPercentage = this.checkExpInput(p1);
this._rampLowPercentage = this.checkExpInput(p2);
@@ -6233,7 +6327,7 @@ env = function () {
};
/**
* Assign a parameter to be controlled by this envelope.
- * If a p5.Sound object is given, then the p5.Env will control its
+ * If a p5.Sound object is given, then the p5.Envelope will control its
* output gain. If multiple inputs are provided, the env will
* control all of them.
*
@@ -6241,7 +6335,7 @@ env = function () {
* @param {Object} [...inputs] A p5.sound object or
* Web Audio Param.
*/
- p5.Env.prototype.setInput = function () {
+ p5.Envelope.prototype.setInput = function () {
for (var i = 0; i < arguments.length; i++) {
this.connect(arguments[i]);
}
@@ -6254,11 +6348,11 @@ env = function () {
* @method setExp
* @param {Boolean} isExp true is exponential, false is linear
*/
- p5.Env.prototype.setExp = function (isExp) {
+ p5.Envelope.prototype.setExp = function (isExp) {
this.isExponential = isExp;
};
//helper method to protect against zero values being sent to exponential functions
- p5.Env.prototype.checkExpInput = function (value) {
+ p5.Envelope.prototype.checkExpInput = function (value) {
if (value <= 0) {
value = 1e-8;
}
@@ -6267,7 +6361,7 @@ env = function () {
/**
* Play tells the envelope to start acting on a given input.
* If the input is a p5.sound object (i.e. AudioIn, Oscillator,
- * SoundFile), then Env will control its output volume.
+ * SoundFile), then Envelope will control its output volume.
* Envelopes can also be used to control any
* Web Audio Audio Param.
@@ -6295,7 +6389,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -6314,7 +6408,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.play = function (unit, secondsFromNow, susTime) {
+ p5.Envelope.prototype.play = function (unit, secondsFromNow, susTime) {
var tFromNow = secondsFromNow || 0;
var susTime = susTime || 0;
if (unit) {
@@ -6355,7 +6449,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -6383,7 +6477,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.triggerAttack = function (unit, secondsFromNow) {
+ p5.Envelope.prototype.triggerAttack = function (unit, secondsFromNow) {
var now = p5sound.audiocontext.currentTime;
var tFromNow = secondsFromNow || 0;
var t = now + tFromNow;
@@ -6459,7 +6553,7 @@ env = function () {
* textAlign(CENTER);
* text('click to play', width/2, height/2);
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime, susPercent, releaseTime);
* env.setRange(attackLevel, releaseLevel);
*
@@ -6487,7 +6581,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.triggerRelease = function (unit, secondsFromNow) {
+ p5.Envelope.prototype.triggerRelease = function (unit, secondsFromNow) {
// only trigger a release if an attack was triggered
if (!this.wasTriggered) {
// this currently causes a bit of trouble:
@@ -6531,7 +6625,7 @@ env = function () {
};
/**
* Exponentially ramp to a value using the first two
- * values from setADSR(attackTime, decayTime)
+ * values from setADSR(attackTime, decayTime)
* as
* time constants for simple exponential ramps.
* If the value is higher than current value, it uses attackTime,
@@ -6556,7 +6650,7 @@ env = function () {
* fill(0,255,0);
* noStroke();
*
- * env = new p5.Env();
+ * env = new p5.Envelope();
* env.setADSR(attackTime, decayTime);
*
* osc = new p5.Oscillator();
@@ -6581,7 +6675,7 @@ env = function () {
* }
*
*/
- p5.Env.prototype.ramp = function (unit, secondsFromNow, v1, v2) {
+ p5.Envelope.prototype.ramp = function (unit, secondsFromNow, v1, v2) {
var now = p5sound.audiocontext.currentTime;
var tFromNow = secondsFromNow || 0;
var t = now + tFromNow;
@@ -6614,7 +6708,7 @@ env = function () {
this.control.setTargetAtTime(destination2, t, this._rampDecayTC);
}
};
- p5.Env.prototype.connect = function (unit) {
+ p5.Envelope.prototype.connect = function (unit) {
this.connection = unit;
// assume we're talking about output gain
// unless given a different audio param
@@ -6630,8 +6724,10 @@ env = function () {
}
this.output.connect(unit);
};
- p5.Env.prototype.disconnect = function () {
- this.output.disconnect();
+ p5.Envelope.prototype.disconnect = function () {
+ if (this.output) {
+ this.output.disconnect();
+ }
};
// Signal Math
/**
@@ -6641,26 +6737,26 @@ env = function () {
*
* @method add
* @param {Number} number Constant number to add
- * @return {p5.Env} Envelope Returns this envelope
+ * @return {p5.Envelope} Envelope Returns this envelope
* with scaled output
*/
- p5.Env.prototype.add = function (num) {
+ p5.Envelope.prototype.add = function (num) {
var add = new Add(num);
var thisChain = this.mathOps.length;
var nextChain = this.output;
return p5.prototype._mathChain(this, add, thisChain, nextChain, Add);
};
/**
- * Multiply the p5.Env's output amplitude
+ * Multiply the p5.Envelope's output amplitude
* by a fixed value. Calling this method
* again will override the initial mult() with new values.
*
* @method mult
* @param {Number} number Constant number to multiply
- * @return {p5.Env} Envelope Returns this envelope
+ * @return {p5.Envelope} Envelope Returns this envelope
* with scaled output
*/
- p5.Env.prototype.mult = function (num) {
+ p5.Envelope.prototype.mult = function (num) {
var mult = new Mult(num);
var thisChain = this.mathOps.length;
var nextChain = this.output;
@@ -6676,31 +6772,35 @@ env = function () {
* @param {Number} inMax input range maximum
* @param {Number} outMin input range minumum
* @param {Number} outMax input range maximum
- * @return {p5.Env} Envelope Returns this envelope
+ * @return {p5.Envelope} Envelope Returns this envelope
* with scaled output
*/
- p5.Env.prototype.scale = function (inMin, inMax, outMin, outMax) {
+ p5.Envelope.prototype.scale = function (inMin, inMax, outMin, outMax) {
var scale = new Scale(inMin, inMax, outMin, outMax);
var thisChain = this.mathOps.length;
var nextChain = this.output;
return p5.prototype._mathChain(this, scale, thisChain, nextChain, Scale);
};
// get rid of the oscillator
- p5.Env.prototype.dispose = function () {
+ p5.Envelope.prototype.dispose = function () {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
this.disconnect();
- try {
+ if (this.control) {
this.control.dispose();
this.control = null;
- } catch (e) {
- console.warn(e, 'already disposed p5.Env');
}
for (var i = 1; i < this.mathOps.length; i++) {
this.mathOps[i].dispose();
}
};
+ // Different name for backwards compatibility, replicates p5.Envelope class
+ p5.Env = function (t1, l1, t2, l2, t3, l3) {
+ console.warn('WARNING: p5.Env is now deprecated and may be removed in future versions. ' + 'Please use the new p5.Envelope instead.');
+ p5.Envelope.call(this, t1, l1, t2, l2, t3, l3);
+ };
+ p5.Env.prototype = Object.create(p5.Envelope.prototype);
}(master, Tone_signal_Add, Tone_signal_Multiply, Tone_signal_Scale, Tone_signal_TimelineSignal, Tone_core_Tone);
var pulse;
'use strict';
@@ -6836,7 +6936,9 @@ pulse = function () {
var t = time || 0;
var now = p5sound.audiocontext.currentTime;
this.oscillator.stop(t + now);
- this.osc2.oscillator.stop(t + now);
+ if (this.osc2.oscillator) {
+ this.osc2.oscillator.stop(t + now);
+ }
this.dcOffset.stop(t + now);
this.started = false;
this.osc2.started = false;
@@ -6985,11 +7087,6 @@ noise = function () {
p5.Noise.prototype.getType = function () {
return this.buffer.type;
};
- /**
- * Start the noise
- *
- * @method start
- */
p5.Noise.prototype.start = function () {
if (this.started) {
this.stop();
@@ -7002,11 +7099,6 @@ noise = function () {
this.noise.start(now);
this.started = true;
};
- /**
- * Stop the noise.
- *
- * @method stop
- */
p5.Noise.prototype.stop = function () {
var now = p5sound.audiocontext.currentTime;
if (this.noise) {
@@ -7014,37 +7106,6 @@ noise = function () {
this.started = false;
}
};
- /**
- * Pan the noise.
- *
- * @method pan
- * @param {Number} panning Number between -1 (left)
- * and 1 (right)
- * @param {Number} timeFromNow schedule this event to happen
- * seconds from now
- */
- /**
- * Set the amplitude of the noise between 0 and 1.0. Or,
- * modulate amplitude with an audio signal such as an oscillator.
- *
- * @method amp
- * @param {Number|Object} volume amplitude between 0 and 1.0
- * or modulating signal/oscillator
- * @param {Number} [rampTime] create a fade that lasts rampTime
- * @param {Number} [timeFromNow] schedule this event to happen
- * seconds from now
- */
- /**
- * Send output to a p5.sound or web audio object
- *
- * @method connect
- * @param {Object} unit
- */
- /**
- * Disconnect all output.
- *
- * @method disconnect
- */
p5.Noise.prototype.dispose = function () {
var now = p5sound.audiocontext.currentTime;
// remove reference from soundArray
@@ -7228,9 +7289,11 @@ audioin = function () {
* @method disconnect
*/
p5.AudioIn.prototype.disconnect = function () {
- this.output.disconnect();
- // stay connected to amplitude even if not outputting to p5
- this.output.connect(this.amplitude.input);
+ if (this.output) {
+ this.output.disconnect();
+ // stay connected to amplitude even if not outputting to p5
+ this.output.connect(this.amplitude.input);
+ }
};
/**
* Read the Amplitude (volume level) of an AudioIn. The AudioIn
@@ -7968,28 +8031,28 @@ effect = function () {
var p5sound = master;
var CrossFade = Tone_component_CrossFade;
/**
- * Effect is a base class for audio effects in p5.
- * This module handles the nodes and methods that are
- * common and useful for current and future effects.
- *
- *
- * This class is extended by p5.Distortion,
- * p5.Compressor,
- * p5.Delay,
- * p5.Filter,
- * p5.Reverb.
- *
- * @class p5.Effect
- * @constructor
- *
- * @param {Object} [ac] Reference to the audio context of the p5 object
- * @param {AudioNode} [input] Gain Node effect wrapper
- * @param {AudioNode} [output] Gain Node effect wrapper
- * @param {Object} [_drywet] Tone.JS CrossFade node (defaults to value: 1)
- * @param {AudioNode} [wet] Effects that extend this class should connect
- * to the wet signal to this gain node, so that dry and wet
- * signals are mixed properly.
- */
+ * Effect is a base class for audio effects in p5.
+ * This module handles the nodes and methods that are
+ * common and useful for current and future effects.
+ *
+ *
+ * This class is extended by p5.Distortion,
+ * p5.Compressor,
+ * p5.Delay,
+ * p5.Filter,
+ * p5.Reverb.
+ *
+ * @class p5.Effect
+ * @constructor
+ *
+ * @param {Object} [ac] Reference to the audio context of the p5 object
+ * @param {AudioNode} [input] Gain Node effect wrapper
+ * @param {AudioNode} [output] Gain Node effect wrapper
+ * @param {Object} [_drywet] Tone.JS CrossFade node (defaults to value: 1)
+ * @param {AudioNode} [wet] Effects that extend this class should connect
+ * to the wet signal to this gain node, so that dry and wet
+ * signals are mixed properly.
+ */
p5.Effect = function () {
this.ac = p5sound.audiocontext;
this.input = this.ac.createGain();
@@ -8014,13 +8077,13 @@ effect = function () {
p5sound.soundArray.push(this);
};
/**
- * Set the output volume of the filter.
- *
- * @method amp
- * @param {Number} [vol] amplitude between 0 and 1.0
- * @param {Number} [rampTime] create a fade that lasts until rampTime
- * @param {Number} [tFromNow] schedule this event to happen in tFromNow seconds
- */
+ * Set the output volume of the filter.
+ *
+ * @method amp
+ * @param {Number} [vol] amplitude between 0 and 1.0
+ * @param {Number} [rampTime] create a fade that lasts until rampTime
+ * @param {Number} [tFromNow] schedule this event to happen in tFromNow seconds
+ */
p5.Effect.prototype.amp = function (vol, rampTime, tFromNow) {
var rampTime = rampTime || 0;
var tFromNow = tFromNow || 0;
@@ -8031,13 +8094,13 @@ effect = function () {
this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime + 0.001);
};
/**
- * Link effects together in a chain
- * Example usage: filter.chain(reverb, delay, panner);
- * May be used with an open-ended number of arguments
- *
- * @method chain
+ * Link effects together in a chain
+ * Example usage: filter.chain(reverb, delay, panner);
+ * May be used with an open-ended number of arguments
+ *
+ * @method chain
* @param {Object} [arguments] Chain together multiple sound objects
- */
+ */
p5.Effect.prototype.chain = function () {
if (arguments.length > 0) {
this.connect(arguments[0]);
@@ -8048,11 +8111,11 @@ effect = function () {
return this;
};
/**
- * Adjust the dry/wet value.
- *
- * @method drywet
- * @param {Number} [fade] The desired drywet value (0 - 1.0)
- */
+ * Adjust the dry/wet value.
+ *
+ * @method drywet
+ * @param {Number} [fade] The desired drywet value (0 - 1.0)
+ */
p5.Effect.prototype.drywet = function (fade) {
if (typeof fade !== 'undefined') {
this._drywet.fade.value = fade;
@@ -8060,36 +8123,46 @@ effect = function () {
return this._drywet.fade.value;
};
/**
- * Send output to a p5.js-sound, Web Audio Node, or use signal to
- * control an AudioParam
- *
- * @method connect
- * @param {Object} unit
- */
+ * Send output to a p5.js-sound, Web Audio Node, or use signal to
+ * control an AudioParam
+ *
+ * @method connect
+ * @param {Object} unit
+ */
p5.Effect.prototype.connect = function (unit) {
var u = unit || p5.soundOut.input;
this.output.connect(u.input ? u.input : u);
};
/**
- * Disconnect all output.
- *
- * @method disconnect
- */
+ * Disconnect all output.
+ *
+ * @method disconnect
+ */
p5.Effect.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
p5.Effect.prototype.dispose = function () {
// remove refernce form soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
- this.input.disconnect();
- this.input = undefined;
- this.output.disconnect();
- this.output = undefined;
- this._drywet.disconnect();
- delete this._drywet;
- this.wet.disconnect();
- delete this.wet;
+ if (this.input) {
+ this.input.disconnect();
+ delete this.input;
+ }
+ if (this.output) {
+ this.output.disconnect();
+ delete this.output;
+ }
+ if (this._drywet) {
+ this._drywet.disconnect();
+ delete this._drywet;
+ }
+ if (this.wet) {
+ this.wet.disconnect();
+ delete this.wet;
+ }
this.ac = undefined;
};
return p5.Effect;
@@ -8326,8 +8399,10 @@ filter = function () {
p5.Filter.prototype.dispose = function () {
// remove reference from soundArray
Effect.prototype.dispose.apply(this);
- this.biquad.disconnect();
- this.biquad = undefined;
+ if (this.biquad) {
+ this.biquad.disconnect();
+ delete this.biquad;
+ }
};
/**
* Constructor: new p5.LowPass()
Filter.
@@ -8410,7 +8485,9 @@ src_eqFilter = function () {
}
};
EQFilter.prototype.disconnect = function () {
- this.biquad.disconnect();
+ if (this.biquad) {
+ this.biquad.disconnect();
+ }
};
EQFilter.prototype.dispose = function () {
// remove reference form soundArray
@@ -8604,10 +8681,12 @@ eq = function () {
};
p5.EQ.prototype.dispose = function () {
Effect.prototype.dispose.apply(this);
- while (this.bands.length > 0) {
- delete this.bands.pop().dispose();
+ if (this.bands) {
+ while (this.bands.length > 0) {
+ delete this.bands.pop().dispose();
+ }
+ delete this.bands;
}
- delete this.bands;
};
return p5.EQ;
}(effect, src_eqFilter);
@@ -8836,8 +8915,10 @@ panner3d = function () {
};
p5.Panner3D.dispose = function () {
Effect.prototype.dispose.apply(this);
- this.panner.disconnect();
- delete this.panner;
+ if (this.panner) {
+ this.panner.disconnect();
+ delete this.panner;
+ }
};
return p5.Panner3D;
}(master, effect);
@@ -9107,7 +9188,7 @@ delay = function () {
*
* // play the noise with an envelope,
* // a series of fades ( time / value pairs )
- * env = new p5.Env(.01, 0.2, .2, .1);
+ * env = new p5.Envelope(.01, 0.2, .2, .1);
* }
*
* // mouseClick triggers envelope
@@ -9351,9 +9432,9 @@ reverb = function () {
* extends p5.Reverb allowing you to recreate the sound of actual physical
* spaces through convolution.
*
- * This class extends p5.Effect.
- * Methods amp(), chain(),
- * drywet(), connect(), and
+ * This class extends p5.Effect.
+ * Methods amp(), chain(),
+ * drywet(), connect(), and
* disconnect() are available.
*
* @class p5.Reverb
@@ -9628,7 +9709,15 @@ reverb = function () {
if (window.location.origin.indexOf('file://') > -1 && window.cordova === 'undefined') {
alert('This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS');
}
- var cReverb = new p5.Convolver(path, callback, errorCallback);
+ var self = this;
+ var cReverb = new p5.Convolver(path, function (buffer) {
+ if (typeof callback === 'function') {
+ callback(buffer);
+ }
+ if (typeof self._decrementPreload === 'function') {
+ self._decrementPreload();
+ }
+ }, errorCallback);
cReverb.impulses = [];
return cReverb;
};
@@ -9814,10 +9903,12 @@ reverb = function () {
this.impulses[i] = null;
}
}
- this.convolverNode.disconnect();
- this.concolverNode = null;
+ if (this.convolverNode) {
+ this.convolverNode.disconnect();
+ this.concolverNode = null;
+ }
};
-}(errorHandler, effect, sndcore);
+}(errorHandler, effect);
/** Tone.js module by Yotam Mann, MIT License 2016 http://opensource.org/licenses/MIT **/
var Tone_core_TimelineState;
Tone_core_TimelineState = function (Tone) {
@@ -10631,8 +10722,9 @@ soundloop = function () {
*/
p5.SoundLoop.prototype.pause = function (timeFromNow) {
var t = timeFromNow || 0;
+ var now = p5sound.audiocontext.currentTime;
if (this.isPlaying) {
- this.clock.pause(t);
+ this.clock.pause(now + t);
this.isPlaying = false;
}
};
@@ -10981,14 +11073,17 @@ compressor = function () {
};
p5.Compressor.prototype.dispose = function () {
Effect.prototype.dispose.apply(this);
- this.compressor.disconnect();
- this.compressor = undefined;
+ if (this.compressor) {
+ this.compressor.disconnect();
+ delete this.compressor;
+ }
};
return p5.Compressor;
}(master, effect, errorHandler);
var soundRecorder;
'use strict';
soundRecorder = function () {
+ // inspiration: recorder.js, Tone.js & typedarray.org
var p5sound = master;
var ac = p5sound.audiocontext;
/**
@@ -11276,7 +11371,7 @@ soundRecorder = function () {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
-}(sndcore, master);
+}(master);
var peakdetect;
'use strict';
peakdetect = function () {
@@ -11327,18 +11422,19 @@ peakdetect = function () {
* var cnv, soundFile, fft, peakDetect;
* var ellipseWidth = 10;
*
+ * function preload() {
+ * soundFile = loadSound('assets/beat.mp3');
+ * }
+ *
* function setup() {
* background(0);
* noStroke();
* fill(255);
* textAlign(CENTER);
*
- * soundFile = loadSound('assets/beat.mp3');
- *
* // p5.PeakDetect requires a p5.FFT
* fft = new p5.FFT();
* peakDetect = new p5.PeakDetect();
- *
* }
*
* function draw() {
@@ -11446,11 +11542,14 @@ peakdetect = function () {
* var cnv, soundFile, fft, peakDetect;
* var ellipseWidth = 0;
*
+ * function preload() {
+ * soundFile = loadSound('assets/beat.mp3');
+ * }
+ *
* function setup() {
* cnv = createCanvas(100,100);
* textAlign(CENTER);
*
- * soundFile = loadSound('assets/beat.mp3');
* fft = new p5.FFT();
* peakDetect = new p5.PeakDetect();
*
@@ -11515,8 +11614,8 @@ gain = function () {
*
* function preload(){
* soundFormats('ogg', 'mp3');
- * sound1 = loadSound('../_files/Damscray_-_Dancing_Tiger_01');
- * sound2 = loadSound('../_files/beat.mp3');
+ * sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01');
+ * sound2 = loadSound('assets/beat.mp3');
* }
*
* function setup() {
@@ -11601,7 +11700,9 @@ gain = function () {
* @method disconnect
*/
p5.Gain.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
/**
* Set the output level of the gain node.
@@ -11625,12 +11726,16 @@ gain = function () {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
- this.output.disconnect();
- this.input.disconnect();
- this.output = undefined;
- this.input = undefined;
+ if (this.output) {
+ this.output.disconnect();
+ delete this.output;
+ }
+ if (this.input) {
+ this.input.disconnect();
+ delete this.input;
+ }
};
-}(master, sndcore);
+}(master);
var audioVoice;
'use strict';
audioVoice = function () {
@@ -11649,30 +11754,6 @@ audioVoice = function () {
this.connect();
p5sound.soundArray.push(this);
};
- /**
- * This method converts midi notes specified as a string "C4", "Eb3"...etc
- * to frequency
- * @private
- * @method _setNote
- * @param {String} note
- */
- p5.AudioVoice.prototype._setNote = function (note) {
- var wholeNotes = {
- A: 21,
- B: 23,
- C: 24,
- D: 26,
- E: 28,
- F: 29,
- G: 31
- };
- var value = wholeNotes[note[0]];
- var octave = typeof Number(note.slice(-1)) === 'number' ? note.slice(-1) : 0;
- value += 12 * octave;
- value = note[1] === '#' ? value + 1 : note[1] === 'b' ? value - 1 : value;
- //return midi value converted to frequency
- return p5.prototype.midiToFreq(value);
- };
p5.AudioVoice.prototype.play = function (note, velocity, secondsFromNow, sustime) {
};
p5.AudioVoice.prototype.triggerAttack = function (note, velocity, secondsFromNow) {
@@ -11698,8 +11779,10 @@ audioVoice = function () {
this.output.disconnect();
};
p5.AudioVoice.prototype.dispose = function () {
- this.output.disconnect();
- delete this.output;
+ if (this.output) {
+ this.output.disconnect();
+ delete this.output;
+ }
};
return p5.AudioVoice;
}(master);
@@ -11708,9 +11791,11 @@ var monosynth;
monosynth = function () {
var p5sound = master;
var AudioVoice = audioVoice;
+ var noteToFreq = helpers.noteToFreq;
+ var DEFAULT_SUSTAIN = 0.15;
/**
- * An MonoSynth is used as a single voice for sound synthesis.
- * This is a class to be used in conjonction with the PolySynth
+ * A MonoSynth is used as a single voice for sound synthesis.
+ * This is a class to be used in conjunction with the PolySynth
* class. Custom synthetisers should be built inheriting from
* this class.
*
@@ -11718,17 +11803,31 @@ monosynth = function () {
* @constructor
* @example
*
- * var monosynth;
- * var x;
+ * var monoSynth;
*
* function setup() {
- * monosynth = new p5.MonoSynth();
- * monosynth.loadPreset('simpleBass');
- * monosynth.play(45,1,x=0,1);
- * monosynth.play(49,1,x+=1,0.25);
- * monosynth.play(50,1,x+=0.25,0.25);
- * monosynth.play(49,1,x+=0.5,0.25);
- * monosynth.play(50,1,x+=0.25,0.25);
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * monoSynth = new p5.MonoSynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // time from now (in seconds)
+ * var time = 0;
+ * // note duration (in seconds)
+ * var dur = 0.25;
+ * // velocity (volume, from 0 to 1)
+ * var v = 0.2;
+ *
+ * monoSynth.play("G3", v, time, dur);
+ * monoSynth.play("C4", v, time += dur, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
* }
*
**/
@@ -11736,7 +11835,7 @@ monosynth = function () {
AudioVoice.call(this);
this.oscillator = new p5.Oscillator();
// this.oscillator.disconnect();
- this.env = new p5.Env();
+ this.env = new p5.Envelope();
this.env.setRange(1, 0);
this.env.setExp(true);
//set params
@@ -11759,46 +11858,83 @@ monosynth = function () {
};
p5.MonoSynth.prototype = Object.create(p5.AudioVoice.prototype);
/**
- * Play tells the MonoSynth to start playing a note. This method schedules
- * the calling of .triggerAttack and .triggerRelease.
- *
- * @method play
- * @param {String | Number} note the note you want to play, specified as a
- * frequency in Hertz (Number) or as a midi
- * value in Note/Octave format ("C4", "Eb3"...etc")
- * See
- * Tone. Defaults to 440 hz.
- * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)
- * @param {Number} [secondsFromNow] time from now (in seconds) at which to play
- * @param {Number} [sustainTime] time to sustain before releasing the envelope
- *
- */
+ * Play tells the MonoSynth to start playing a note. This method schedules
+ * the calling of .triggerAttack and .triggerRelease.
+ *
+ * @method play
+ * @param {String | Number} note the note you want to play, specified as a
+ * frequency in Hertz (Number) or as a midi
+ * value in Note/Octave format ("C4", "Eb3"...etc")
+ * See
+ * Tone. Defaults to 440 hz.
+ * @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)
+ * @param {Number} [secondsFromNow] time from now (in seconds) at which to play
+ * @param {Number} [sustainTime] time to sustain before releasing the envelope
+ * @example
+ *
+ * var monoSynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * monoSynth = new p5.MonoSynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // time from now (in seconds)
+ * var time = 0;
+ * // note duration (in seconds)
+ * var dur = 1/6;
+ * // note velocity (volume, from 0 to 1)
+ * var v = random();
+ *
+ * monoSynth.play("Fb3", v, 0, dur);
+ * monoSynth.play("Gb3", v, time += dur, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ *
+ */
p5.MonoSynth.prototype.play = function (note, velocity, secondsFromNow, susTime) {
- // set range of env (TO DO: allow this to be scheduled in advance)
- var susTime = susTime || this.sustain;
- this.susTime = susTime;
- this.triggerAttack(note, velocity, secondsFromNow);
- this.triggerRelease(secondsFromNow + susTime);
+ this.triggerAttack(note, velocity, ~~secondsFromNow);
+ this.triggerRelease(~~secondsFromNow + (susTime || DEFAULT_SUSTAIN));
};
/**
* Trigger the Attack, and Decay portion of the Envelope.
* Similar to holding down a key on a piano, but it will
* hold the sustain level until you let go.
*
- * @param {String | Number} note the note you want to play, specified as a
- * frequency in Hertz (Number) or as a midi
+ * @param {String | Number} note the note you want to play, specified as a
+ * frequency in Hertz (Number) or as a midi
* value in Note/Octave format ("C4", "Eb3"...etc")
* See
* Tone. Defaults to 440 hz
* @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)
* @param {Number} [secondsFromNow] time from now (in seconds) at which to play
* @method triggerAttack
+ * @example
+ *
+ * var monoSynth = new p5.MonoSynth();
+ *
+ * function mousePressed() {
+ * monoSynth.triggerAttack("E3");
+ * }
+ *
+ * function mouseReleased() {
+ * monoSynth.triggerRelease();
+ * }
+ *
*/
p5.MonoSynth.prototype.triggerAttack = function (note, velocity, secondsFromNow) {
- var secondsFromNow = secondsFromNow || 0;
- //triggerAttack uses ._setNote to convert a midi string to a frequency if necessary
- var freq = typeof note === 'string' ? this._setNote(note) : typeof note === 'number' ? note : 440;
- var vel = velocity || 1;
+ var secondsFromNow = ~~secondsFromNow;
+ var freq = noteToFreq(note);
+ var vel = velocity || 0.1;
this._isOn = true;
this.oscillator.freq(freq, 0, secondsFromNow);
this.env.ramp(this.output, secondsFromNow, vel);
@@ -11810,6 +11946,18 @@ monosynth = function () {
*
* @param {Number} secondsFromNow time to trigger the release
* @method triggerRelease
+ * @example
+ *
+ * var monoSynth = new p5.MonoSynth();
+ *
+ * function mousePressed() {
+ * monoSynth.triggerAttack("E3");
+ * }
+ *
+ * function mouseReleased() {
+ * monoSynth.triggerRelease();
+ * }
+ *
*/
p5.MonoSynth.prototype.triggerRelease = function (secondsFromNow) {
var secondsFromNow = secondsFromNow || 0;
@@ -11917,7 +12065,9 @@ monosynth = function () {
* @method disconnect
*/
p5.MonoSynth.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
/**
* Get rid of the MonoSynth and free up its resources / memory.
@@ -11926,58 +12076,79 @@ monosynth = function () {
*/
p5.MonoSynth.prototype.dispose = function () {
AudioVoice.prototype.dispose.apply(this);
- this.filter.dispose();
- this.env.dispose();
- try {
+ if (this.filter) {
+ this.filter.dispose();
+ }
+ if (this.env) {
+ this.env.dispose();
+ }
+ if (this.oscillator) {
this.oscillator.dispose();
- } catch (e) {
- console.error('mono synth default oscillator already disposed');
}
};
-}(master, audioVoice);
+}(master, audioVoice, helpers);
var polysynth;
'use strict';
polysynth = function () {
var p5sound = master;
var TimelineSignal = Tone_signal_TimelineSignal;
+ var noteToFreq = helpers.noteToFreq;
/**
* An AudioVoice is used as a single voice for sound synthesis.
* The PolySynth class holds an array of AudioVoice, and deals
* with voices allocations, with setting notes to be played, and
- * parameters to be set.
+ * parameters to be set.
*
* @class p5.PolySynth
* @constructor
- *
+ *
* @param {Number} [synthVoice] A monophonic synth voice inheriting
* the AudioVoice class. Defaults to p5.MonoSynth
- * @param {Number} [polyValue] Number of voices, defaults to 8;
- *
- *
+ * @param {Number} [maxVoices] Number of voices, defaults to 8;
* @example
*
- * var polysynth;
+ * var polySynth;
+ *
* function setup() {
- * polysynth = new p5.PolySynth();
- * polysynth.play(53,1,0,3);
- * polysynth.play(60,1,0,2.9);
- * polysynth.play(69,1,0,3);
- * polysynth.play(71,1,0,3);
- * polysynth.play(74,1,0,3);
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * polySynth = new p5.PolySynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // note duration (in seconds)
+ * var dur = 1.5;
+ *
+ * // time from now (in seconds)
+ * var time = 0;
+ *
+ * // velocity (volume, from 0 to 1)
+ * var vel = 0.1;
+ *
+ * // notes can overlap with each other
+ * polySynth.play("G2", vel, 0, dur);
+ * polySynth.play("C3", vel, time += 1/3, dur);
+ * polySynth.play("G3", vel, time += 1/3, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
* }
*
- *
**/
- p5.PolySynth = function (audioVoice, polyValue) {
- //audiovoices will contain polyValue many monophonic synths
+ p5.PolySynth = function (audioVoice, maxVoices) {
+ //audiovoices will contain maxVoices many monophonic synths
this.audiovoices = [];
/**
- * An object that holds information about which notes have been played and
+ * An object that holds information about which notes have been played and
* which notes are currently being played. New notes are added as keys
* on the fly. While a note has been attacked, but not released, the value of the
* key is the audiovoice which is generating that note. When notes are released,
- * the value of the key becomes undefined.
- * @property notes
+ * the value of the key becomes undefined.
+ * @property notes
*/
this.notes = {};
//indices of the most recently used, and least recently used audiovoice
@@ -11987,7 +12158,7 @@ polysynth = function () {
* A PolySynth must have at least 1 voice, defaults to 8
* @property polyvalue
*/
- this.polyValue = polyValue || 8;
+ this.maxVoices = maxVoices || 8;
/**
* Monosynth that generates the sound for each note that is triggered. The
* p5.PolySynth defaults to using the p5.MonoSynth as its voice.
@@ -12013,7 +12184,7 @@ polysynth = function () {
* @method _allocateVoices
*/
p5.PolySynth.prototype._allocateVoices = function () {
- for (var i = 0; i < this.polyValue; i++) {
+ for (var i = 0; i < this.maxVoices; i++) {
this.audiovoices.push(new this.AudioVoice());
this.audiovoices[i].disconnect();
this.audiovoices[i].connect(this.output);
@@ -12021,24 +12192,56 @@ polysynth = function () {
};
/**
* Play a note by triggering noteAttack and noteRelease with sustain time
- *
+ *
* @method play
* @param {Number} [note] midi note to play (ranging from 0 to 127 - 60 being a middle C)
* @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)
* @param {Number} [secondsFromNow] time from now (in seconds) at which to play
* @param {Number} [sustainTime] time to sustain before releasing the envelope
+ * @example
+ *
+ * var polySynth;
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * cnv.mousePressed(playSynth);
+ *
+ * polySynth = new p5.PolySynth();
+ *
+ * textAlign(CENTER);
+ * text('click to play', width/2, height/2);
+ * }
+ *
+ * function playSynth() {
+ * // note duration (in seconds)
+ * var dur = 0.1;
+ *
+ * // time from now (in seconds)
+ * var time = 0;
+ *
+ * // velocity (volume, from 0 to 1)
+ * var vel = 0.1;
+ *
+ * polySynth.play("G2", vel, 0, dur);
+ * polySynth.play("C3", vel, 0, dur);
+ * polySynth.play("G3", vel, 0, dur);
+ *
+ * background(random(255), random(255), 255);
+ * text('click to play', width/2, height/2);
+ * }
+ *
*/
p5.PolySynth.prototype.play = function (note, velocity, secondsFromNow, susTime) {
var susTime = susTime || 1;
this.noteAttack(note, velocity, secondsFromNow);
this.noteRelease(note, secondsFromNow + susTime);
};
- /**
+ /**
* noteADSR sets the envelope for a specific note that has just been triggered.
* Using this method modifies the envelope of whichever audiovoice is being used
* to play the desired note. The envelope should be reset before noteRelease is called
* in order to prevent the modified envelope from being used on other notes.
- *
+ *
* @method noteADSR
* @param {Number} [note] Midi note on which ADSR should be set.
* @param {Number} [attackTime] Time (in seconds before envelope
@@ -12061,12 +12264,11 @@ polysynth = function () {
var t = now + timeFromNow;
this.audiovoices[this.notes[note].getValueAtTime(t)].setADSR(a, d, s, r);
};
- /**
+ /**
* Set the PolySynths global envelope. This method modifies the envelopes of each
* monosynth so that all notes are played with this envelope.
- *
+ *
* @method setADSR
- * @param {Number} [note] Midi note on which ADSR should be set.
* @param {Number} [attackTime] Time (in seconds before envelope
* reaches Attack Level
* @param {Number} [decayTime] Time (in seconds) before envelope
@@ -12089,60 +12291,77 @@ polysynth = function () {
/**
* Trigger the Attack, and Decay portion of a MonoSynth.
* Similar to holding down a key on a piano, but it will
- * hold the sustain level until you let go.
+ * hold the sustain level until you let go.
*
* @method noteAttack
* @param {Number} [note] midi note on which attack should be triggered.
* @param {Number} [velocity] velocity of the note to play (ranging from 0 to 1)/
* @param {Number} [secondsFromNow] time from now (in seconds)
- *
+ * @example
+ *
+ * var polySynth = new p5.PolySynth();
+ * var pitches = ["G", "D", "G", "C"];
+ * var octaves = [2, 3, 4];
+ *
+ * function mousePressed() {
+ * // play a chord: multiple notes at the same time
+ * for (var i = 0; i < 4; i++) {
+ * var note = random(pitches) + random(octaves);
+ * polySynth.noteAttack(note, 0.1);
+ * }
+ * }
+ *
+ * function mouseReleased() {
+ * // release all voices
+ * polySynth.noteRelease();
+ * }
+ *
*/
p5.PolySynth.prototype.noteAttack = function (_note, _velocity, secondsFromNow) {
- var now = p5sound.audiocontext.currentTime;
//this value goes to the audiovoices which handle their own scheduling
- var tFromNow = secondsFromNow || 0;
+ var secondsFromNow = ~~secondsFromNow;
//this value is used by this._voicesInUse
- var t = now + tFromNow;
+ var acTime = p5sound.audiocontext.currentTime + secondsFromNow;
//Convert note to frequency if necessary. This is because entries into this.notes
//should be based on frequency for the sake of consistency.
- var note = typeof _note === 'string' ? this.AudioVoice.prototype._setNote(_note) : typeof _note === 'number' ? _note : 440;
- var velocity = _velocity === undefined ? 1 : _velocity;
+ var note = noteToFreq(_note);
+ var velocity = _velocity || 0.1;
var currentVoice;
//Release the note if it is already playing
- if (this.notes[note] !== undefined && this.notes[note].getValueAtTime(t) !== null) {
+ if (this.notes[note] && this.notes[note].getValueAtTime(acTime) !== null) {
this.noteRelease(note, 0);
}
//Check to see how many voices are in use at the time the note will start
- if (this._voicesInUse.getValueAtTime(t) < this.polyValue) {
- currentVoice = this._voicesInUse.getValueAtTime(t);
+ if (this._voicesInUse.getValueAtTime(acTime) < this.maxVoices) {
+ currentVoice = Math.max(~~this._voicesInUse.getValueAtTime(acTime), 0);
} else {
currentVoice = this._oldest;
var oldestNote = p5.prototype.freqToMidi(this.audiovoices[this._oldest].oscillator.freq().value);
this.noteRelease(oldestNote);
- this._oldest = (this._oldest + 1) % (this.polyValue - 1);
+ this._oldest = (this._oldest + 1) % (this.maxVoices - 1);
}
- //Overrite the entry in the notes object. A note (frequency value)
+ //Overrite the entry in the notes object. A note (frequency value)
//corresponds to the index of the audiovoice that is playing it
this.notes[note] = new TimelineSignal();
- this.notes[note].setValueAtTime(currentVoice, t);
+ this.notes[note].setValueAtTime(currentVoice, acTime);
//Find the scheduled change in this._voicesInUse that will be previous to this new note
//Add 1 and schedule this value at time 't', when this note will start playing
- var previousVal = this._voicesInUse._searchBefore(t) === null ? 0 : this._voicesInUse._searchBefore(t).value;
- this._voicesInUse.setValueAtTime(previousVal + 1, t);
+ var previousVal = this._voicesInUse._searchBefore(acTime) === null ? 0 : this._voicesInUse._searchBefore(acTime).value;
+ this._voicesInUse.setValueAtTime(previousVal + 1, acTime);
//Then update all scheduled values that follow to increase by 1
- this._updateAfter(t, 1);
+ this._updateAfter(acTime, 1);
this._newest = currentVoice;
//The audiovoice handles the actual scheduling of the note
if (typeof velocity === 'number') {
- var maxRange = 1 / this._voicesInUse.getValueAtTime(t) * 2;
+ var maxRange = 1 / this._voicesInUse.getValueAtTime(acTime) * 2;
velocity = velocity > maxRange ? maxRange : velocity;
}
- this.audiovoices[currentVoice].triggerAttack(note, velocity, tFromNow);
+ this.audiovoices[currentVoice].triggerAttack(note, velocity, secondsFromNow);
};
/**
* Private method to ensure accurate values of this._voicesInUse
* Any time a new value is scheduled, it is necessary to increment all subsequent
- * scheduledValues after attack, and decrement all subsequent
+ * scheduledValues after attack, and decrement all subsequent
* scheduledValues after release
*
* @private
@@ -12163,30 +12382,65 @@ polysynth = function () {
* Trigger the Release of an AudioVoice note. This is similar to releasing
* the key on a piano and letting the sound fade according to the
* release level and release time.
- *
+ *
* @method noteRelease
* @param {Number} [note] midi note on which attack should be triggered.
+ * If no value is provided, all notes will be released.
* @param {Number} [secondsFromNow] time to trigger the release
- *
+ * @example
+ *
+ * var pitches = ["G", "D", "G", "C"];
+ * var octaves = [2, 3, 4];
+ * var polySynth = new p5.PolySynth();
+ *
+ * function mousePressed() {
+ * // play a chord: multiple notes at the same time
+ * for (var i = 0; i < 4; i++) {
+ * var note = random(pitches) + random(octaves);
+ * polySynth.noteAttack(note, 0.1);
+ * }
+ * }
+ *
+ * function mouseReleased() {
+ * // release all voices
+ * polySynth.noteRelease();
+ * }
+ *
+ *
*/
p5.PolySynth.prototype.noteRelease = function (_note, secondsFromNow) {
- //Make sure note is in frequency inorder to query the this.notes object
- var note = typeof _note === 'string' ? this.AudioVoice.prototype._setNote(_note) : typeof _note === 'number' ? _note : this.audiovoices[this._newest].oscillator.freq().value;
var now = p5sound.audiocontext.currentTime;
var tFromNow = secondsFromNow || 0;
var t = now + tFromNow;
- if (this.notes[note].getValueAtTime(t) === null) {
+ // if a note value is not provided, release all voices
+ if (!_note) {
+ this.audiovoices.forEach(function (voice) {
+ voice.triggerRelease(tFromNow);
+ });
+ this._voicesInUse.setValueAtTime(0, t);
+ for (var n in this.notes) {
+ this.notes[n].dispose();
+ delete this.notes[n];
+ }
+ return;
+ }
+ //Make sure note is in frequency inorder to query the this.notes object
+ var note = noteToFreq(_note);
+ if (!this.notes[note] || this.notes[note].getValueAtTime(t) === null) {
console.warn('Cannot release a note that is not already playing');
} else {
//Find the scheduled change in this._voicesInUse that will be previous to this new note
//subtract 1 and schedule this value at time 't', when this note will stop playing
- var previousVal = this._voicesInUse._searchBefore(t) === null ? 0 : this._voicesInUse._searchBefore(t).value;
+ var previousVal = Math.max(~~this._voicesInUse.getValueAtTime(t).value, 1);
this._voicesInUse.setValueAtTime(previousVal - 1, t);
- //Then update all scheduled values that follow to decrease by 1
- this._updateAfter(t, -1);
+ //Then update all scheduled values that follow to decrease by 1 but never go below 0
+ if (previousVal > 0) {
+ this._updateAfter(t, -1);
+ }
this.audiovoices[this.notes[note].getValueAtTime(t)].triggerRelease(tFromNow);
- this.notes[note].setValueAtTime(null, t);
- this._newest = this._newest === 0 ? 0 : (this._newest - 1) % (this.polyValue - 1);
+ this.notes[note].dispose();
+ delete this.notes[note];
+ this._newest = this._newest === 0 ? 0 : (this._newest - 1) % (this.maxVoices - 1);
}
};
/**
@@ -12205,7 +12459,9 @@ polysynth = function () {
* @method disconnect
*/
p5.PolySynth.prototype.disconnect = function () {
- this.output.disconnect();
+ if (this.output) {
+ this.output.disconnect();
+ }
};
/**
* Get rid of the MonoSynth and free up its resources / memory.
@@ -12216,10 +12472,12 @@ polysynth = function () {
this.audiovoices.forEach(function (voice) {
voice.dispose();
});
- this.output.disconnect();
- delete this.output;
+ if (this.output) {
+ this.output.disconnect();
+ delete this.output;
+ }
};
-}(master, Tone_signal_TimelineSignal, sndcore);
+}(master, Tone_signal_TimelineSignal, helpers);
var distortion;
'use strict';
distortion = function () {
@@ -12340,14 +12598,16 @@ distortion = function () {
};
p5.Distortion.prototype.dispose = function () {
Effect.prototype.dispose.apply(this);
- this.waveShaperNode.disconnect();
- this.waveShaperNode = null;
+ if (this.waveShaperNode) {
+ this.waveShaperNode.disconnect();
+ this.waveShaperNode = null;
+ }
};
}(effect);
var src_app;
'use strict';
src_app = function () {
- var p5SOUND = sndcore;
+ var p5SOUND = master;
return p5SOUND;
-}(sndcore, master, helpers, errorHandler, panner, soundfile, amplitude, fft, signal, oscillator, env, pulse, noise, audioin, filter, eq, panner3d, listener3d, delay, reverb, metro, looper, soundloop, compressor, soundRecorder, peakdetect, gain, monosynth, polysynth, distortion, audioVoice, monosynth, polysynth);
+}(shims, audiocontext, master, helpers, errorHandler, panner, soundfile, amplitude, fft, signal, oscillator, envelope, pulse, noise, audioin, filter, eq, panner3d, listener3d, delay, reverb, metro, looper, soundloop, compressor, soundRecorder, peakdetect, gain, monosynth, polysynth, distortion, audioVoice, monosynth, polysynth);
}));
\ No newline at end of file
diff --git a/lib/p5.sound.min.js b/lib/p5.sound.min.js
index 393a0d47..345428a8 100644
--- a/lib/p5.sound.min.js
+++ b/lib/p5.sound.min.js
@@ -1,4 +1,4 @@
-/*! p5.sound.min.js v0.3.7 2018-01-19 */
+/*! p5.sound.min.js v0.3.8 2018-06-15 */
/**
* p5.sound
@@ -21,8 +21,8 @@
* Web Audio API: http://w3.org/TR/webaudio/
*/
-!function(t,e){"function"==typeof define&&define.amd?define("p5.sound",["p5"],function(t){e(t)}):e("object"==typeof exports?require("../p5"):t.p5)}(this,function(t){var e;e=function(){!function(){function t(t){t&&(t.setTargetAtTime||(t.setTargetAtTime=t.setTargetValueAtTime))}window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=window.webkitAudioContext,"function"!=typeof AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),"function"!=typeof AudioContext.prototype.createDelay&&(AudioContext.prototype.createDelay=AudioContext.prototype.createDelayNode),"function"!=typeof AudioContext.prototype.createScriptProcessor&&(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode),"function"!=typeof AudioContext.prototype.createPeriodicWave&&(AudioContext.prototype.createPeriodicWave=AudioContext.prototype.createWaveTable),AudioContext.prototype.internal_createGain=AudioContext.prototype.createGain,AudioContext.prototype.createGain=function(){var e=this.internal_createGain();return t(e.gain),e},AudioContext.prototype.internal_createDelay=AudioContext.prototype.createDelay,AudioContext.prototype.createDelay=function(e){var i=e?this.internal_createDelay(e):this.internal_createDelay();return t(i.delayTime),i},AudioContext.prototype.internal_createBufferSource=AudioContext.prototype.createBufferSource,AudioContext.prototype.createBufferSource=function(){var e=this.internal_createBufferSource();return e.start?(e.internal_start=e.start,e.start=function(t,i,n){"undefined"!=typeof n?e.internal_start(t||0,i,n):e.internal_start(t||0,i||0)}):e.start=function(t,e,i){e||i?this.noteGrainOn(t||0,e,i):this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},t(e.playbackRate),e},AudioContext.prototype.internal_createDynamicsCompressor=AudioContext.prototype.createDynamicsCompressor,AudioContext.prototype.createDynamicsCompressor=function(){var e=this.internal_createDynamicsCompressor();return t(e.threshold),t(e.knee),t(e.ratio),t(e.reduction),t(e.attack),t(e.release),e},AudioContext.prototype.internal_createBiquadFilter=AudioContext.prototype.createBiquadFilter,AudioContext.prototype.createBiquadFilter=function(){var e=this.internal_createBiquadFilter();return t(e.frequency),t(e.detune),t(e.Q),t(e.gain),e},"function"!=typeof AudioContext.prototype.createOscillator&&(AudioContext.prototype.internal_createOscillator=AudioContext.prototype.createOscillator,AudioContext.prototype.createOscillator=function(){var e=this.internal_createOscillator();return e.start?(e.internal_start=e.start,e.start=function(t){e.internal_start(t||0)}):e.start=function(t){this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},e.setPeriodicWave||(e.setPeriodicWave=e.setWaveTable),t(e.frequency),t(e.detune),e})),window.hasOwnProperty("webkitOfflineAudioContext")&&!window.hasOwnProperty("OfflineAudioContext")&&(window.OfflineAudioContext=window.webkitOfflineAudioContext)}(window);var e=new window.AudioContext;t.prototype.getAudioContext=function(){return e},navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var i=document.createElement("audio");t.prototype.isSupported=function(){return!!i.canPlayType};var n=function(){return!!i.canPlayType&&i.canPlayType('audio/ogg; codecs="vorbis"')},o=function(){return!!i.canPlayType&&i.canPlayType("audio/mpeg;")},r=function(){return!!i.canPlayType&&i.canPlayType('audio/wav; codecs="1"')},s=function(){return!!i.canPlayType&&(i.canPlayType("audio/x-m4a;")||i.canPlayType("audio/aac;"))},a=function(){return!!i.canPlayType&&i.canPlayType("audio/x-aiff;")};t.prototype.isFileSupported=function(t){switch(t.toLowerCase()){case"mp3":return o();case"wav":return r();case"ogg":return n();case"aac":case"m4a":case"mp4":return s();case"aif":case"aiff":return a();default:return!1}};var u=navigator.userAgent.match(/(iPad|iPhone|iPod)/g)?!0:!1;if(u){var c=!1,p=function(){if(!c){var t=e.createBuffer(1,1,22050),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),console.log("start ios!"),"running"===e.state&&(c=!0)}};document.addEventListener("touchend",p,!1),document.addEventListener("touchstart",p,!1)}}();var i;i=function(){var e=function(){var e=t.prototype.getAudioContext();this.input=e.createGain(),this.output=e.createGain(),this.limiter=e.createDynamicsCompressor(),this.limiter.threshold.value=0,this.limiter.ratio.value=20,this.audiocontext=e,this.output.disconnect(),this.input.connect(this.limiter),this.limiter.connect(this.output),this.meter=e.createGain(),this.fftMeter=e.createGain(),this.output.connect(this.meter),this.output.connect(this.fftMeter),this.output.connect(this.audiocontext.destination),this.soundArray=[],this.parts=[],this.extensions=[]},i=new e;return t.prototype.getMasterVolume=function(){return i.output.gain.value},t.prototype.masterVolume=function(t,e,n){if("number"==typeof t){var e=e||0,n=n||0,o=i.audiocontext.currentTime,r=i.output.gain.value;i.output.gain.cancelScheduledValues(o+n),i.output.gain.linearRampToValueAtTime(r,o+n),i.output.gain.linearRampToValueAtTime(t,o+n+e)}else{if(!t)return i.output.gain;t.connect(i.output.gain)}},t.prototype.soundOut=t.soundOut=i,t.soundOut._silentNode=i.audiocontext.createGain(),t.soundOut._silentNode.gain.value=0,t.soundOut._silentNode.connect(i.audiocontext.destination),i}();var n;n=function(){var e=i;return t.prototype.sampleRate=function(){return e.audiocontext.sampleRate},t.prototype.freqToMidi=function(t){var e=Math.log(t/440)/Math.log(2),i=Math.round(12*e)+69;return i},t.prototype.midiToFreq=function(t){return 440*Math.pow(2,(t-69)/12)},t.prototype.soundFormats=function(){e.extensions=[];for(var t=0;t-1))throw arguments[t]+" is not a valid sound format!";e.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(o))n=n;else for(var r=n.split("."),s=r[r.length-1],a=0;a1?(this.splitter=n.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=n.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var i=e||0,o=n.currentTime+i,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=n.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output.disconnect()})}(i);var s;s=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new d(r,o);i[o]=s,o+=6e3}o++}return i}function r(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function s(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=u(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(r){throw r}}),i}function a(t,e,i,n){for(var o=[],r=Object.keys(t).sort(),s=0;s.01?!0:void 0})}function u(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}var c=o,p=i,h=p.audiocontext,l=n.midiToFreq;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=p.audiocontext.createGain(),this.output=p.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,p.input,2),(this.url||this.file)&&this.load(i,n),p.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){}},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status)h.decodeAudioData(o.response,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)},function(){var t=new c("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)});else{var r=new c("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new c("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){h.decodeAudioData(r.result,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)})},r.onerror=function(t){onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){var r,s,a=this,u=p.audiocontext.currentTime,c=t||0;if(0>c&&(c=0),c+=u,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(c),this._counterNode.stop(c)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=p.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=l(t)/l(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/h.sampleRate:this._lastPos/h.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n)},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/h.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=p.audiocontext.currentTime,e=p.soundArray.indexOf(this);if(p.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var f=function(t){const e=t.length,i=h.createBuffer(1,t.length,h.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=h.currentTime,n=h.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),delete e._scopeNode.onaudioprocess,delete e._scopeNode),e._scopeNode=h.createScriptProcessor(256,1,1),n.buffer=f(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.onaudioprocess=function(t){var i=t.inputBuffer.getChannelData(0);e._lastPos=i[i.length-1]||0,e._onTimeUpdate(e._lastPos)},n},t.SoundFile.prototype._initSourceNode=function(){var t=h.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,i,n,o){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=i||.9,f=l,d=n||.22,m=o||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(i){var n=i.renderedBuffer,o=n.getChannelData(0);do h=e(o,f),f-=.005;while(Object.keys(h).length=d);var u=r(h),c=s(u,n.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=a(h,p[0].tempo,n.sampleRate,l);t(y)}};var d=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},m=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new m(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];n.id===t&&this.cues.splice(i,1)}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e}}(e,o,i,n);var a;a=function(){var e=i;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input.disconnect(),this.output.disconnect(),this.input=this.processor=void 0,this.output=void 0}}(i);var u;u=function(){var e=i;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,o=0;oi){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hi1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;te;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(c);var l;l=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(c);var f;f=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(c);var d;d=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(c);var m;m=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(c);var y;y=function(t){"use strict";return t.Emitter=function(){this._events={}},t.extend(t.Emitter),t.Emitter.prototype.on=function(t,e){for(var i=t.split(/\W+/),n=0;nn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(c,_);var b;b=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(c,h,g,_);var x;x=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(c,b);var S;S=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null,this._param=null,this},t.Multiply}(c,b);var w;w=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(c,x,S);var A;A=function(){var e=b,n=x,o=S,r=w,s=c,a=i;s.setContext(a.audiocontext),t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,o.prototype.fade=e.prototype.fade,n.prototype.fade=e.prototype.fade,r.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},o.prototype.setInput=e.prototype.setInput,n.prototype.setInput=e.prototype.setInput,r.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new n(t);return this.connect(e),e},o.prototype.add=e.prototype.add,n.prototype.add=e.prototype.add,r.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new o(t);return this.connect(e),e},o.prototype.mult=e.prototype.mult,n.prototype.mult=e.prototype.mult,r.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,o){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(o,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new r(s,a);return this.connect(u),u},o.prototype.scale=e.prototype.scale,n.prototype.scale=e.prototype.scale,r.prototype.scale=e.prototype.scale}(b,x,S,w,c,i);var P;P=function(){var e=i,n=x,o=S,r=w;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime;this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),this.oscillator=void 0),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;
-for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output.disconnect(),this.panner.disconnect(),this.output.connect(this.panner),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var s=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new n(t),i=this.mathOps.length-1,o=this.output;return s(this,e,i,o,n)},t.Oscillator.prototype.mult=function(t){var e=new o(t),i=this.mathOps.length-1,n=this.output;return s(this,e,i,n,o)},t.Oscillator.prototype.scale=function(e,i,n,o){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(o,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new r(a,u),p=this.mathOps.length-1,h=this.output;return s(this,c,p,h,r)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(i,x,S,w);var k;k=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(c);var O;O=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(c,b);var F;F=function(){var e=i,n=x,o=S,r=w,s=O,a=c;a.setContext(e.audiocontext),t.Env=function(t,i,n,o,r,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=r||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new s,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Env.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Env.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Env.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Env.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Env.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Env.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Env.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Env.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Env.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Env.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Env.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Env.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Env.prototype.disconnect=function(){this.output.disconnect()},t.Env.prototype.add=function(e){var i=new n(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,o,r,n)},t.Env.prototype.mult=function(e){var i=new o(e),n=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,n,r,o)},t.Env.prototype.scale=function(e,i,n,o){var s=new r(e,i,n,o),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,r)},t.Env.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect();try{this.control.dispose(),this.control=null}catch(i){console.warn(i,"already disposed p5.Env")}for(var n=1;no;o++)i[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var n=i;t.Pulse=function(i,o){t.Oscillator.call(this,i,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(i),this.dNode=n.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=n.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=i||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,i){var o=n.audiocontext.currentTime,r=i||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=n.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=n.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,i=n.audiocontext.currentTime;this.oscillator.stop(e+i),this.osc2.oscillator.stop(e+i),this.dcOffset.stop(e+i),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,i){if("number"==typeof t){this.f=t;var o=n.audiocontext.currentTime,e=e||0,i=i||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+i),this.oscillator.frequency.exponentialRampToValueAtTime(t,i+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+i),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,i+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(i,P);var M;M=function(){var e=i;t.Noise=function(e){var i;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,i="brown"===e?r:"pink"===e?o:n,this.buffer=i},t.Noise.prototype=Object.create(t.Oscillator.prototype);var n=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),o=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),r=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=n;break;case"pink":this.buffer=o;break;case"brown":this.buffer=r;break;default:this.buffer=n}if(this.started){var i=e.audiocontext.currentTime;this.stop(i),this.start(i+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(i);var V;V=function(){var e=i;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output.disconnect(),this.output.connect(this.amplitude.input)},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(c,b,S);var D;D=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(c,E,R);var N;N=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(c,h);var B;B=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(c,h,S);var U;U=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(c);var I;I=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(c,h);var G;G=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add)},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.value=t,this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad.disconnect(),this.biquad=void 0},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(i,Z);var Y;Y=function(){var e=X,n=i,o=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return o.prototype=Object.create(e.prototype),o.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},o.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},o.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},o.prototype.disconnect=function(){this.biquad.disconnect()},o.prototype.dispose=function(){var t=n.soundArray.indexOf(this);n.soundArray.splice(t,1),this.disconnect(),delete this.biquad},o}(X,i);var z;z=function(){var e=Z,i=Y;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands},t.EQ}(Z,Y);var W;W=function(){var e=Z;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner.disconnect(),delete this.panner},t.Panner3D}(i,Z);var Q;Q=function(){var e=i;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(i,Z);var H;H=function(){var e=X,i=Z;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(X,Z);var $;$=function(){var e=o,i=Z;t.Reverb=function(){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this.convolverNode.buffer=r},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this.convolverNode&&(this.convolverNode.buffer=null,this.convolverNode=null)},t.Convolver=function(t,e,n){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),t?(this.impulses=[],this._loadBuffer(t,e,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=new t.Convolver(e,i,n);return o.impulses=[],o},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r.convolverNode.buffer=e.audioBuffer,n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(c,O,J,y);var tt;tt=function(){var e=i,n=K;t.Metro=function(){this.clock=new n({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var n=i,o=120;t.prototype.setBPM=function(t,e){o=t;for(var i in n.parts)n.parts[i]&&n.parts[i].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,i){this.length=e||0,this.partStep=0,this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=i||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(o),n.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var e=t||0;this.isPlaying&&(this.clock.pause(e),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){
-if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(i,K);var nt;nt=function(){"use strict";var e=Z;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor.disconnect(),this.compressor=void 0},t.Compressor}(i,Z,o);var ot;ot=function(){function e(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function n(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=i,r=o.audiocontext;t.SoundRecorder=function(){this.input=r.createGain(),this.output=r.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=r.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),o.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=r.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*r.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=o.soundArray.indexOf(this);o.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(i,o){var r,s;r=i.buffer.getChannelData(0),s=i.buffer.numberOfChannels>1?i.buffer.getChannelData(1):r;var a=e(r,s),u=new window.ArrayBuffer(44+2*a.length),c=new window.DataView(u);n(c,0,"RIFF"),c.setUint32(4,36+2*a.length,!0),n(c,8,"WAVE"),n(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,2,!0),c.setUint32(24,44100,!0),c.setUint32(28,176400,!0),c.setUint16(32,4,!0),c.setUint16(34,16,!0),n(c,36,"data"),c.setUint32(40,2*a.length,!0);for(var p=a.length,h=44,l=1,f=0;p>f;f++)c.setInt16(h,a[f]*(32767*l),!0),h+=2;t.prototype.writeFile([c],o,"wav")}}(e,i);var rt;rt=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var st;st=function(){var e=i;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output.disconnect(),this.input.disconnect(),this.output=void 0,this.input=void 0}}(i,e);var at;at=function(){var e=i;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype._setNote=function(e){var i={A:21,B:23,C:24,D:26,E:28,F:29,G:31},n=i[e[0]],o="number"==typeof Number(e.slice(-1))?e.slice(-1):0;return n+=12*o,n="#"===e[1]?n+1:"b"===e[1]?n-1:n,t.prototype.midiToFreq(n)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output.disconnect(),delete this.output},t.AudioVoice}(i);var ut;ut=function(){var e=i,n=at;t.MonoSynth=function(){n.call(this),this.oscillator=new t.Oscillator,this.env=new t.Env,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.filter=new t.Filter("highpass"),this.filter.set(5,1),this.oscillator.disconnect(),this.oscillator.connect(this.filter),this.env.disconnect(),this.env.setInput(this.oscillator),this.filter.connect(this.output),this.oscillator.start(),this.connect(),this._isOn=!1,e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){var n=n||this.sustain;this.susTime=n,this.triggerAttack(t,e,i),this.triggerRelease(i+n)},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=i||0,n="string"==typeof t?this._setNote(t):"number"==typeof t?t:440,o=e||1;this._isOn=!0,this.oscillator.freq(n,0,i),this.env.ramp(this.output,i,o)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output,t,0),this._isOn=!1},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){n.prototype.dispose.apply(this),this.filter.dispose(),this.env.dispose();try{this.oscillator.dispose()}catch(t){console.error("mono synth default oscillator already disposed")}}}(i,at);var ct;ct=function(){var e=i,n=O;t.PolySynth=function(i,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.polyValue=o||8,this.AudioVoice=void 0===i?t.MonoSynth:i,this._voicesInUse=new n(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;td?d:h}this.audiovoices[s].triggerAttack(p,h,u)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var n="string"==typeof t?this.AudioVoice.prototype._setNote(t):"number"==typeof t?t:this.audiovoices[this._newest].oscillator.freq().value,o=e.audiocontext.currentTime,r=i||0,s=o+r;if(null===this.notes[n].getValueAtTime(s))console.warn("Cannot release a note that is not already playing");else{var a=null===this._voicesInUse._searchBefore(s)?0:this._voicesInUse._searchBefore(s).value;this._voicesInUse.setValueAtTime(a-1,s),this._updateAfter(s,-1),this.audiovoices[this.notes[n].getValueAtTime(s)].triggerRelease(r),this.notes[n].setValueAtTime(null,s),this._newest=0===this._newest?0:(this._newest-1)%(this.polyValue-1)}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output.disconnect(),delete this.output}}(i,O,e);var pt;pt=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=Z;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode.disconnect(),this.waveShaperNode=null}}(Z);var ht;ht=function(){var t=e;return t}(e,i,n,o,r,s,a,u,A,P,F,q,M,V,X,z,W,Q,H,$,tt,et,it,nt,ot,rt,st,ut,ct,pt,at,ut,ct)});
\ No newline at end of file
+!function(t,e){"function"==typeof define&&define.amd?define("p5.sound",["p5"],function(t){e(t)}):e("object"==typeof exports?require("../p5"):t.p5)}(this,function(t){var e;e=function(){!function(){function t(t){t&&(t.setTargetAtTime||(t.setTargetAtTime=t.setTargetValueAtTime))}window.hasOwnProperty("webkitAudioContext")&&!window.hasOwnProperty("AudioContext")&&(window.AudioContext=window.webkitAudioContext,"function"!=typeof AudioContext.prototype.createGain&&(AudioContext.prototype.createGain=AudioContext.prototype.createGainNode),"function"!=typeof AudioContext.prototype.createDelay&&(AudioContext.prototype.createDelay=AudioContext.prototype.createDelayNode),"function"!=typeof AudioContext.prototype.createScriptProcessor&&(AudioContext.prototype.createScriptProcessor=AudioContext.prototype.createJavaScriptNode),"function"!=typeof AudioContext.prototype.createPeriodicWave&&(AudioContext.prototype.createPeriodicWave=AudioContext.prototype.createWaveTable),AudioContext.prototype.internal_createGain=AudioContext.prototype.createGain,AudioContext.prototype.createGain=function(){var e=this.internal_createGain();return t(e.gain),e},AudioContext.prototype.internal_createDelay=AudioContext.prototype.createDelay,AudioContext.prototype.createDelay=function(e){var i=e?this.internal_createDelay(e):this.internal_createDelay();return t(i.delayTime),i},AudioContext.prototype.internal_createBufferSource=AudioContext.prototype.createBufferSource,AudioContext.prototype.createBufferSource=function(){var e=this.internal_createBufferSource();return e.start?(e.internal_start=e.start,e.start=function(t,i,n){"undefined"!=typeof n?e.internal_start(t||0,i,n):e.internal_start(t||0,i||0)}):e.start=function(t,e,i){e||i?this.noteGrainOn(t||0,e,i):this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},t(e.playbackRate),e},AudioContext.prototype.internal_createDynamicsCompressor=AudioContext.prototype.createDynamicsCompressor,AudioContext.prototype.createDynamicsCompressor=function(){var e=this.internal_createDynamicsCompressor();return t(e.threshold),t(e.knee),t(e.ratio),t(e.reduction),t(e.attack),t(e.release),e},AudioContext.prototype.internal_createBiquadFilter=AudioContext.prototype.createBiquadFilter,AudioContext.prototype.createBiquadFilter=function(){var e=this.internal_createBiquadFilter();return t(e.frequency),t(e.detune),t(e.Q),t(e.gain),e},"function"!=typeof AudioContext.prototype.createOscillator&&(AudioContext.prototype.internal_createOscillator=AudioContext.prototype.createOscillator,AudioContext.prototype.createOscillator=function(){var e=this.internal_createOscillator();return e.start?(e.internal_start=e.start,e.start=function(t){e.internal_start(t||0)}):e.start=function(t){this.noteOn(t||0)},e.stop?(e.internal_stop=e.stop,e.stop=function(t){e.internal_stop(t||0)}):e.stop=function(t){this.noteOff(t||0)},e.setPeriodicWave||(e.setPeriodicWave=e.setWaveTable),t(e.frequency),t(e.detune),e})),window.hasOwnProperty("webkitOfflineAudioContext")&&!window.hasOwnProperty("OfflineAudioContext")&&(window.OfflineAudioContext=window.webkitOfflineAudioContext)}(window),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var e=document.createElement("audio");t.prototype.isSupported=function(){return!!e.canPlayType};var i=function(){return!!e.canPlayType&&e.canPlayType('audio/ogg; codecs="vorbis"')},n=function(){return!!e.canPlayType&&e.canPlayType("audio/mpeg;")},o=function(){return!!e.canPlayType&&e.canPlayType('audio/wav; codecs="1"')},r=function(){return!!e.canPlayType&&(e.canPlayType("audio/x-m4a;")||e.canPlayType("audio/aac;"))},s=function(){return!!e.canPlayType&&e.canPlayType("audio/x-aiff;")};t.prototype.isFileSupported=function(t){switch(t.toLowerCase()){case"mp3":return n();case"wav":return o();case"ogg":return i();case"aac":case"m4a":case"mp4":return r();case"aif":case"aiff":return s();default:return!1}}}();var i;i=function(){var e=new window.AudioContext;t.prototype.getAudioContext=function(){return e};var i=navigator.userAgent.match(/(iPad|iPhone|iPod)/g)?!0:!1;if(i){var n=!1,o=function(){if(!n){var t=e.createBuffer(1,1,22050),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),console.log("start ios!"),"running"===e.state&&(n=!0)}};document.addEventListener("touchend",o,!1),document.addEventListener("touchstart",o,!1)}return e}();var n;n=function(){var e=function(){var e=t.prototype.getAudioContext();this.input=e.createGain(),this.output=e.createGain(),this.limiter=e.createDynamicsCompressor(),this.limiter.threshold.value=0,this.limiter.ratio.value=20,this.audiocontext=e,this.output.disconnect(),this.input.connect(this.limiter),this.limiter.connect(this.output),this.meter=e.createGain(),this.fftMeter=e.createGain(),this.output.connect(this.meter),this.output.connect(this.fftMeter),this.output.connect(this.audiocontext.destination),this.soundArray=[],this.parts=[],this.extensions=[]},i=new e;return t.prototype.getMasterVolume=function(){return i.output.gain.value},t.prototype.masterVolume=function(t,e,n){if("number"==typeof t){var e=e||0,n=n||0,o=i.audiocontext.currentTime,r=i.output.gain.value;i.output.gain.cancelScheduledValues(o+n),i.output.gain.linearRampToValueAtTime(r,o+n),i.output.gain.linearRampToValueAtTime(t,o+n+e)}else{if(!t)return i.output.gain;t.connect(i.output.gain)}},t.prototype.soundOut=t.soundOut=i,t.soundOut._silentNode=i.audiocontext.createGain(),t.soundOut._silentNode.gain.value=0,t.soundOut._silentNode.connect(i.audiocontext.destination),i}();var o;o=function(){var e=n;t.prototype.sampleRate=function(){return e.audiocontext.sampleRate},t.prototype.freqToMidi=function(t){var e=Math.log(t/440)/Math.log(2),i=Math.round(12*e)+69;return i};var i=t.prototype.midiToFreq=function(t){return 440*Math.pow(2,(t-69)/12)};return noteToFreq=function(t){if("string"!=typeof t)return t;var e={A:21,B:23,C:24,D:26,E:28,F:29,G:31},n=e[t[0].toUpperCase()],o=~~t.slice(-1);switch(n+=12*(o-1),t[1]){case"#":n+=1;break;case"b":n-=1}return i(n)},t.prototype.soundFormats=function(){e.extensions=[];for(var t=0;t-1))throw arguments[t]+" is not a valid sound format!";e.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(o))n=n;else for(var r=n.split("."),s=r[r.length-1],a=0;a1?(this.splitter=i.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=i.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var n=e||0,o=i.currentTime+n,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=i.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output&&this.output.disconnect()})}(n);var a;a=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new d(r,o);i[o]=s,o+=6e3}o++}return i}function i(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function s(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=u(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(r){throw r}}),i}function a(t,e,i,n){for(var o=[],r=Object.keys(t).sort(),s=0;s.01?!0:void 0})}function u(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}var c=r,p=n,h=p.audiocontext,l=o.midiToFreq;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=p.audiocontext.createGain(),this.output=p.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,p.input,2),(this.url||this.file)&&this.load(i,n),p.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){}},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),"function"==typeof r._decrementPreload&&r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status)h.decodeAudioData(o.response,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)},function(){var t=new c("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)});else{var r=new c("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new c("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){h.decodeAudioData(r.result,function(e){i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i)})},r.onerror=function(t){onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){if(!this.output)return void console.warn("SoundFile.play() called after dispose");var r,s,a=this,u=p.audiocontext.currentTime,c=t||0;if(0>c&&(c=0),c+=u,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(c),this._counterNode.stop(c)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=p.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=l(t)/l(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/h.sampleRate:this._lastPos/h.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n)},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/h.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=p.audiocontext.currentTime,e=p.soundArray.indexOf(this);if(p.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var f=function(t){const e=t.length,i=h.createBuffer(1,t.length,h.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=h.currentTime,n=h.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),delete e._scopeNode.onaudioprocess,delete e._scopeNode),e._scopeNode=h.createScriptProcessor(256,1,1),n.buffer=f(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.onaudioprocess=function(t){var i=t.inputBuffer.getChannelData(0);e._lastPos=i[i.length-1]||0,e._onTimeUpdate(e._lastPos)},n},t.SoundFile.prototype._initSourceNode=function(){var t=h.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,n,o,r){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=n||.9,f=l,d=o||.22,m=r||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(n){var o=n.renderedBuffer,r=o.getChannelData(0);do h=e(r,f),f-=.005;while(Object.keys(h).length=d);var u=i(h),c=s(u,o.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=a(h,p[0].tempo,o.sampleRate,l);t(y)}};var d=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},m=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new m(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];n.id===t&&this.cues.splice(i,1)}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e}}(r,n,o);var u;u=function(){var e=n;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input&&(this.input.disconnect(),delete this.input),this.output&&(this.output.disconnect(),delete this.output),delete this.processor}}(n);var c;c=function(){var e=n;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,o=0;oi){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hi1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;te;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(p);var f;f=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(p);var d;d=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(p);var m;m=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(p);var y;y=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(p);var v;v=function(t){"use strict";return t.Emitter=function(){this._events={}},t.extend(t.Emitter),t.Emitter.prototype.on=function(t,e){for(var i=t.split(/\W+/),n=0;nn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(p,T);var x;x=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(p,l,_,T);var S;S=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(p,x);var w;w=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null,this._param=null,this},t.Multiply}(p,x);var A;A=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(p,S,w);var P;P=function(){var e=x,i=S,o=w,r=A,s=p,a=n;s.setContext(a.audiocontext),t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,o.prototype.fade=e.prototype.fade,i.prototype.fade=e.prototype.fade,r.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},o.prototype.setInput=e.prototype.setInput,i.prototype.setInput=e.prototype.setInput,r.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new i(t);return this.connect(e),e},o.prototype.add=e.prototype.add,i.prototype.add=e.prototype.add,r.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new o(t);return this.connect(e),e},o.prototype.mult=e.prototype.mult,i.prototype.mult=e.prototype.mult,r.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,o){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(o,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new r(s,a);return this.connect(u),u},o.prototype.scale=e.prototype.scale,i.prototype.scale=e.prototype.scale,r.prototype.scale=e.prototype.scale}(x,S,w,A,p,n);var k;k=function(){var e=n,i=S,o=w,r=A;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime;
+this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),delete this.oscillator),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output&&this.output.disconnect(),this.panner&&(this.panner.disconnect(),this.output&&this.output.connect(this.panner)),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var s=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new i(t),n=this.mathOps.length-1,o=this.output;return s(this,e,n,o,i)},t.Oscillator.prototype.mult=function(t){var e=new o(t),i=this.mathOps.length-1,n=this.output;return s(this,e,i,n,o)},t.Oscillator.prototype.scale=function(e,i,n,o){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(o,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new r(a,u),p=this.mathOps.length-1,h=this.output;return s(this,c,p,h,r)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(n,S,w,A);var O;O=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(p);var F;F=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(p,x);var q;q=function(){var e=n,i=S,o=w,r=A,s=F,a=p;a.setContext(e.audiocontext),t.Envelope=function(t,i,n,o,r,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=r||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new s,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Envelope.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Envelope.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Envelope.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Envelope.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Envelope.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Envelope.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Envelope.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Envelope.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Envelope.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Envelope.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Envelope.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Envelope.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Envelope.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Envelope.prototype.add=function(e){var n=new i(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,n,o,r,i)},t.Envelope.prototype.mult=function(e){var i=new o(e),n=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,n,r,o)},t.Envelope.prototype.scale=function(e,i,n,o){var s=new r(e,i,n,o),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,r)},t.Envelope.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect(),this.control&&(this.control.dispose(),this.control=null);for(var i=1;io;o++)n[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var i=n;t.Pulse=function(n,o){t.Oscillator.call(this,n,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(n),this.dNode=i.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=i.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=n||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,n){var o=i.audiocontext.currentTime,r=n||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=i.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=i.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,n=i.audiocontext.currentTime;this.oscillator.stop(e+n),this.osc2.oscillator&&this.osc2.oscillator.stop(e+n),this.dcOffset.stop(e+n),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,n){if("number"==typeof t){this.f=t;var o=i.audiocontext.currentTime,e=e||0,n=n||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+n),this.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+n),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(n,k);var V;V=function(){var e=n;t.Noise=function(e){var n;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,n="brown"===e?r:"pink"===e?o:i,this.buffer=n},t.Noise.prototype=Object.create(t.Oscillator.prototype);var i=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),o=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),r=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=i;break;case"pink":this.buffer=o;break;case"brown":this.buffer=r;break;default:this.buffer=i}if(this.started){var n=e.audiocontext.currentTime;this.stop(n),this.start(n+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(n);var E;E=function(){var e=n;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output&&(this.output.disconnect(),this.output.connect(this.amplitude.input))},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(p,x,w);var N;N=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(p,D,R);var B;B=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(p,l);var U;U=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(p,l,w);var I;I=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(p);var G;G=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(p,l);var L;L=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add)
+},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.value=t,this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad&&(this.biquad.disconnect(),delete this.biquad)},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(n,X);var z;z=function(){var e=Y,i=n,o=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return o.prototype=Object.create(e.prototype),o.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},o.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},o.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},o.prototype.disconnect=function(){this.biquad&&this.biquad.disconnect()},o.prototype.dispose=function(){var t=i.soundArray.indexOf(this);i.soundArray.splice(t,1),this.disconnect(),delete this.biquad},o}(Y,n);var W;W=function(){var e=X,i=z;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands}},t.EQ}(X,z);var Q;Q=function(){var e=X;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner&&(this.panner.disconnect(),delete this.panner)},t.Panner3D}(n,X);var H;H=function(){var e=n;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(n,X);var $;$=function(){var e=Y,i=X;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(Y,X);var J;J=function(){var e=r,i=X;t.Reverb=function(){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this.convolverNode.buffer=r},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this.convolverNode&&(this.convolverNode.buffer=null,this.convolverNode=null)},t.Convolver=function(t,e,n){i.call(this),this.convolverNode=this.ac.createConvolver(),this.input.gain.value=.5,this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet),t?(this.impulses=[],this._loadBuffer(t,e,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=this,r=new t.Convolver(e,function(t){"function"==typeof i&&i(t),"function"==typeof o._decrementPreload&&o._decrementPreload()},n);return r.impulses=[],r},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r.convolverNode.buffer=e.audioBuffer,n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(p,F,K,v);var et;et=function(){var e=n,i=tt;t.Metro=function(){this.clock=new i({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var i=n,o=120;t.prototype.setBPM=function(t,e){o=t;for(var n in i.parts)i.parts[n]&&i.parts[n].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,n){this.length=e||0,this.partStep=0,this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=n||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(o),i.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.pause(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(n,tt);var ot;ot=function(){"use strict";var e=X;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor&&(this.compressor.disconnect(),delete this.compressor)},t.Compressor}(n,X,r);var rt;rt=function(){function e(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function i(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=n,r=o.audiocontext;t.SoundRecorder=function(){this.input=r.createGain(),this.output=r.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=r.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),o.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=r.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*r.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=o.soundArray.indexOf(this);o.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(n,o){var r,s;r=n.buffer.getChannelData(0),s=n.buffer.numberOfChannels>1?n.buffer.getChannelData(1):r;var a=e(r,s),u=new window.ArrayBuffer(44+2*a.length),c=new window.DataView(u);i(c,0,"RIFF"),c.setUint32(4,36+2*a.length,!0),i(c,8,"WAVE"),i(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,2,!0),c.setUint32(24,44100,!0),c.setUint32(28,176400,!0),c.setUint16(32,4,!0),c.setUint16(34,16,!0),i(c,36,"data"),c.setUint32(40,2*a.length,!0);for(var p=a.length,h=44,l=1,f=0;p>f;f++)c.setInt16(h,a[f]*(32767*l),!0),h+=2;t.prototype.writeFile([c],o,"wav")}}(n);var st;st=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var at;at=function(){var e=n;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output&&(this.output.disconnect(),delete this.output),this.input&&(this.input.disconnect(),delete this.input)}}(n);var ut;ut=function(){var e=n;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output&&(this.output.disconnect(),delete this.output)},t.AudioVoice}(n);var ct;ct=function(){var e=n,i=ut,r=o.noteToFreq,s=.15;t.MonoSynth=function(){i.call(this),this.oscillator=new t.Oscillator,this.env=new t.Envelope,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.filter=new t.Filter("highpass"),this.filter.set(5,1),this.oscillator.disconnect(),this.oscillator.connect(this.filter),this.env.disconnect(),this.env.setInput(this.oscillator),this.filter.connect(this.output),this.oscillator.start(),this.connect(),this._isOn=!1,e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){this.triggerAttack(t,e,~~i),this.triggerRelease(~~i+(n||s))},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=~~i,n=r(t),o=e||.1;this._isOn=!0,this.oscillator.freq(n,0,i),this.env.ramp(this.output,i,o)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output,t,0),this._isOn=!1},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){i.prototype.dispose.apply(this),this.filter&&this.filter.dispose(),this.env&&this.env.dispose(),this.oscillator&&this.oscillator.dispose()}}(n,ut,o);var pt;pt=function(){var e=n,i=F,r=o.noteToFreq;t.PolySynth=function(n,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.maxVoices=o||8,this.AudioVoice=void 0===n?t.MonoSynth:n,this._voicesInUse=new i(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;tf?f:p}this.audiovoices[a].triggerAttack(c,p,s)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var n=e.audiocontext.currentTime,o=i||0,s=n+o;if(t){var a=r(t);if(this.notes[a]&&null!==this.notes[a].getValueAtTime(s)){var u=Math.max(~~this._voicesInUse.getValueAtTime(s).value,1);this._voicesInUse.setValueAtTime(u-1,s),u>0&&this._updateAfter(s,-1),this.audiovoices[this.notes[a].getValueAtTime(s)].triggerRelease(o),this.notes[a].dispose(),delete this.notes[a],this._newest=0===this._newest?0:(this._newest-1)%(this.maxVoices-1)}else console.warn("Cannot release a note that is not already playing")}else{this.audiovoices.forEach(function(t){t.triggerRelease(o)}),this._voicesInUse.setValueAtTime(0,s);for(var c in this.notes)this.notes[c].dispose(),delete this.notes[c]}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output&&(this.output.disconnect(),delete this.output)}}(n,F,o);var ht;ht=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=X;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode&&(this.waveShaperNode.disconnect(),this.waveShaperNode=null)}}(X);var lt;lt=function(){var t=n;return t}(e,i,n,o,r,s,a,u,c,P,k,q,M,V,E,Y,W,Q,H,$,J,et,it,nt,ot,rt,st,at,ct,pt,ht,ut,ct,pt)});
\ No newline at end of file
diff --git a/package.json b/package.json
index d626f35a..5d81cfa3 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"type": "git",
"url": "https://github.com/processing/p5.js-sound.git"
},
- "version": "0.3.7",
+ "version": "0.3.8",
"license": "MIT",
"devDependencies": {
"almond": "~0.2.7",