Sound synthesizer using Manipulate
First let me observe that your coding style makes debugging difficult, I highly recommend breaking giant expressions into manageable pieces.
Second, in the code below I have used a different definition for the segments. Your version:
$y=(x-x_1)^{curvature}\frac{y_2-y_1}{x_2-x_1}+y_1$
does not give an amplitude of $y_2$ at $x=x_2$ if $curvature\neq1$. I don't know if that's intentional but it seemed wrong to me. Instead I have used:
$y=(\frac{x-x_1}{x_2-x_1})^{curvature}(y_2-y_1)+y_1$
Since each segment is defined the same way, I defined a function segment
. This takes the start and end times and amplitudes, and the curvature parameter, and returns a {value, condition} suitable for Piecewise
. I also pulled out the definition for the volume. Within the Manipulate I used p
and s
for the peak and sustain amplitudes, and also t1
to t5
to represent the segment boundaries. This helps to make the contents of the Piecewise expression more readable.
segment[t_, t1_, t2_, a1_, a2_, g_] :=
{a1 + (a2 - a1) ((t - t1)/(t2 - t1))^g, t1 < t <= t2}
vol[d_, v_] := d Piecewise[{{10^(v/20), -120 < v <= 12}, {0, v == -120}}]
Manipulate[
Module[{t1, t2, t3, t4, t5, p, s},
{t1, t2, t3, t4, t5} = n5 Accumulate[{n0, n1, n2, n3, n4}];
p = vol[n6, n11];
s = p n7;
Plot[Piecewise[{
{0, time <= t1},
segment[time, t1, t2, 0, p, n8],
segment[time, t2, t3, p, s, n9],
segment[time, t3, t4, s, s, 1],
segment[time, t4, t5, s, 0, n10],
{0, time > t5}
}], {time, 0, t5},
AxesLabel -> {"Time", "Amplitude"}]
],
{{n0, 500, "Delay time"}, 0, 5000, 1/1000},
{{n1, 500, "Attack time"}, 1/1000, 5000, 1/1000},
{{n2, 500, "Decay time"}, 1/1000, 5000, 1/1000},
{{n3, 500, "Sustain time"}, 1/1000, 5000, 1/1000},
{{n4, 500, "Release time"}, 1/1000, 5000, 1/1000},
{{n5, 1, "Envelope lenght"}, 1/100, 2, 1/100},
{{n6, 1, "Envelope depth"}, -1, 1, 1/100},
{{n7, 1/2, "Sustain amplitude"}, 0, 1, 1/100},
{{n8, 1, "Attack time slope"}, 1/100, 2, 1/100},
{{n9, 1, "Decay time slope"}, 1/100, 2, 1/100},
{{n10, 1, "Release time slope"}, 1/100, 2, 1/100},
{{n11, 0, "Volume"}, -120, 12, 1/10}]