%  A Wavetable synthesis demonstration
%  using linear crossfading

%  Author: Andreas Floros
%  Digital Audio Processing Applications Group
%  Dept. of Audiovisual Arts, Ionian University
%  v.1.0 - Last Modified: 22/03/2009.

clc;
clear;

% Define basic sinewave frequencies
f1 = 440;
f2 = 500;

% Define the sampling frequency
fs = 22050;

% Create a single sine wave of  frequency f1
y1 = SynthesizeWave(f1, 1/f1, 0.9, fs, 'sine');

% Create a single Saw waves of  frequencie f2
y2 = SynthesizeWave(f2, 1/f2, 0.9, fs, 'saw');

% Merge the above waves
ywave = [y1 ; y2]';

% Create Cross fade half width of wave y1 for xfade window
xfadewidth = floor( fs / ( f1 * 2 ) );
ramp1 = ( 0 : xfadewidth ) / xfadewidth;
ramp2 = 1 - ramp1;

% Apply the crossfade centered over the join of y1 and y2
pad = ( fs / f1 ) + ( fs / f2 ) - 2.5 * xfadewidth;
xramp1 = [ones(1,1.5*xfadewidth) , ramp2, zeros(1,pad)];
xramp2 = [zeros(1,1.5*xfadewidth) , ramp1, ones(1,pad)];

% Create two period waveforms to fade between
ywave2 = [y1' , zeros(1,fs/f2)];
ytemp = [zeros(1,fs/f1), y2'];

% do xfade
% add two waves together over the period modulated by xfade ramps (recall
% .* to multiply matrices element by element NOT MATRIX mutliplication
ywave2 = xramp1.*ywave2 + xramp2.*ytemp;

% Now plot everything
figure
plot(y1,'b-');
hold on
plot(y2,'g-');

figure
subplot(3,1,1);
plot(ywave);
hold off
set(gca,'fontsize',14);
ylabel('Amplitude'); 
title('Two Waves');
set(gca,'fontsize',14);

subplot(3,1,2);
plot(xramp1);
hold on
plot(xramp2,'r')
hold off
set(gca,'fontsize',14);
ylabel('Amplitude'); 
title('Crossfade Masks');
set(gca,'fontsize',14);

subplot(3,1,3);
plot(ywave2);
set(gca,'fontsize',14);
ylabel('Amplitude'); 
title('WaveTable Synthesis');
set(gca,'fontsize',14);

% Now play everything
LoopSound(y1,fs,10*fs/f1);
pause;
LoopSound(y2,fs,10*fs/f2);
pause;
LoopSound(ywave2, fs, 10 * fs / (f1 + f2) );