% A Matlab script to demonstrate a very simple additive synthesis example.

clear;
fs = 44100;               % sample rate
Ts = 1/fs;                % sample period
Tmax = 3.0;               % total time duration
N = ceil(fs*Tmax);        % total samples to compute
tsamples = (0:N-1)*Ts;

% Create an amplitude envelope
ax = [0 .3 .7 1.0];        % time breakpoints over duration Tmax
a1 = [0.0 1.0 0.8 0.0];    % corresponding amplitude values at breakpoints
aenv1 = interp1(ax*Tmax, a1, tsamples);  % scale the time steps to milliseconds

% Create a slight frequency deviation envelope
freq = 220;
fx = [0 0.3 0.6 1.0];       % time breakpoints over duration Tmax
f1 = [1.0 0.999 1.001 1.0]; % corresponding frequency variations at breakpoints
fenv1 = interp1(fx*Tmax, f1, tsamples);

y = zeros(1, N);
for n = 1:N
  for f = 1:length(freq)
      y(n) = y(n) + aenv1(n)*sin(2*pi*fenv1(n)*freq(f)*n*Ts);
  end
end

soundsc(y, fs)