% Digital Audio Course 
% © 2014 Prof. Mario Malcangi

% Frequency Modulation Synthesis (Using Sin amplitude and frequency jitter)
% Sound synthesis by modulating the frequency of a carrier tone

clear;
close all;

% Digital format ----------------------------------------------------------

Fs=8000;        % Sampling rate (Hz)
Ts=1/Fs;        % Sampling Period (s)      

% Sound to be synthesized (test pattern)-----------------------------------

F0=440;                % Carrier frequency
%A=0:0.0001:1-0.0001;  % Amplitude envelope (attack)
%A=1;                  % Amplitude envelope (sustain)
A=1:-0.0002:0;         % Amplitude envelope (decay)
X=size(A);             % Envelope duration
N=X(1,2);
Fmod=F0*pi;              % Modulation frequency                   
I=4;                   % Modulation index 
for(n=0:N)
    dF(n+1)=I*sin(2*pi*Fmod*n*Ts);
end

% Start FMSynth ----------------------------------------------------

for n=0:N-1         % n is the time index (t=n*Ts)
    f=(F0+dF(n+1));
    x(n+1)=A(n+1)*sin(2*pi*f*n*Ts);      % to speed up use sin table lookup
end

% Show results ------------------------------------------------------------

%figure;
TscaleW=0:Ts:(N*Ts)-Ts;  % Windowed signal time scale
subplot(3,1,2);
plot(TscaleW,x);    % Plot the windowed signal
xlabel ('time (s) ');
ylabel ('Amplitude');
legend('Windowed frame');
 sound(x,Fs)


X = fft(x);        % Compute spectrum of x
m = 2*abs(X)/length(x);        % Magnitude

Fscale=0:Fs/(length(X)):(Fs/2);
subplot(3,1,1);
plot(Fscale,m(1:fix(length(X)/2+1)));    % Plot the amplitude spectrum
xlabel ('frequency (Hz) ');
ylabel ('Amplitude');
legend('Module spectrum');

k=100;
%while(1)
TscaleW=0:Ts:(N/1000*Ts)-Ts;  % Windowed signal time scale
subplot(3,1,3);
plot(TscaleW,x(fix((k-1)*(N/1000))+1:fix((k*(N/1000)))));    % Plot the windowed signal
xlabel ('time (s) ');
ylabel ('Amplitude');
legend('Waveform');
%k=k+1;
%end

