Created
March 12, 2019 12:19
-
-
Save iccir/9de0b7ddc90f66d35a0664b7b947df2b to your computer and use it in GitHub Desktop.
Envelope in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Envelope { | |
constructor(type, strength, fromValue, toValue, sampleCount) | |
{ | |
this._generate(type, strength, fromValue, toValue, sampleCount); | |
} | |
_generate(type, strength, fromValue, toValue, sampleCount) | |
{ | |
let result = new Float32Array(sampleCount); | |
let concaveDown = strength < 0; | |
if (concaveDown) strength = -strength; | |
if (type == "quadratic") { | |
for (let i = 0; i < sampleCount; i++) { | |
let x = i / sampleCount; | |
result[i] = x * x; | |
} | |
} else if (type == "cubic") { | |
for (let i = 0; i < sampleCount; i++) { | |
let x = i / sampleCount; | |
result[i] = x * x * x; | |
} | |
} else { | |
let x = Math.pow(10.0, -120.0 / 20.0); | |
let multiplier = Math.pow(1 / x, 1 / sampleCount); | |
for (let i = 0; i < sampleCount; i++) { | |
result[i] = x; | |
x *= multiplier; | |
} | |
} | |
// Mix in linear | |
if (strength < 1) { | |
let iStrength = 1.0 - strength; | |
for (let i = 0; i < sampleCount; i++) { | |
result[i] = strength * result[i] + iStrength * (i/sampleCount); | |
} | |
} | |
// If concaveDown, flip horizontally and vertically | |
if (concaveDown) { | |
for (let i = 0; i < sampleCount / 2; i++) { | |
let i2 = sampleCount - i - 1; | |
let tmp = result[i]; | |
result[i] = 1.0 - result[i2]; | |
result[i2] = 1.0 - tmp; | |
} | |
} | |
let toMinusFrom = toValue - fromValue; | |
for (let i = 0; i < sampleCount; i++) { | |
result[i] = fromValue + result[i] * toMinusFrom; | |
} | |
this._array = result; | |
} | |
apply(sampleArray, startIndex) | |
{ | |
if (!sampleArray) return; | |
if (startIndex === undefined || (startIndex < 0)) { | |
startIndex = 0; | |
} | |
let myArray = this._array; | |
let endIndex = startIndex + myArray.length; | |
if (endIndex > sampleArray.length) { | |
endIndex = sampleArray.length; | |
} | |
let m = 0; | |
for (let s = startIndex; s < endIndex; s++) { | |
sampleArray[s] *= myArray[m++]; | |
} | |
} | |
} | |
export default Envelope; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment