% FM1.m
%
% A Matlab script to calculate frequency modulated waveforms and
% view their spectra.
%
% by Gary Scavone, McGill University, 2004.

clear all;

% Signal parameters
fs = 44100;
Ts = 1/fs;
dur = 4.0;      % seconds
t = 0:Ts:dur;    % time vector

% FM parameters
fc = 2000;      % center freq
fm = 100;
Imin = 0;
Imax = 20;
I = t.*(Imax - Imin)/dur + Imin;

if 0 % use standard formula with modulation index
  y = sin(2*pi*fc*t + I.*sin(2*pi*fm*t));
else % use instantaneous frequency
  iFreq = fc + (I*fm).*sin(2*pi*fm*t);
  phi1 = filter(2 * pi * Ts, [1 -1], iFreq); % phase accumulation and scaling
  %phi1 = 2*pi*Ts*cumsum(iFreq); % same as above but different function
  y = sin(phi1);
end

plot(t, y);

sound(0.5*y, fs);

dospectrum = input('\nPlot spectrum? Y/[N]:\n\n', 's');

if dospectrum == 'Y'
  specgram(y, 512, fs, [], 256)
end
