% Tuneup #3

% Copy this file into a Matlab script window, add your code and answers to the
% questions as Matlab comments, hit "Publish", and upload the resulting PDF file
% to this page for the tune-up assignment.  Please do not submit a link to a file
% but instead upload the file itself.   Late penalty: 2 points per minute late.

% 1. Download the recording ‘violin-C4.wav’ of a violin playing ‘C’ in the fourth
% octave (‘C4’) on the Western scale from Prof. Dan Ellis' (Columbia University) at
%     https://www.ee.columbia.edu/~dpwe/sounds/instruments/
% Please place the file in your MATLAB directory or in a directory on your
% MATLAB path.  The principal frequency of ‘C4’ is 261.63 Hz.

% 2. Please play and plot the audio signal, and describe what you hear.

% Read the contents of the audio file
waveFilename = 'violin-C4.wav';
[instrumentSound, fs] = audioread(waveFilename);

% Play back the recording with automatic scaling
soundsc(instrumentSound, fs);

% Plot the waveform in the time domain
N = length(instrumentSound);
Ts = 1/fs;
Tmax = (N-1)*Ts;
t = 0 : Ts : Tmax;
figure;
plot(t, instrumentSound);
xlabel('Time [s]');
ylabel('Signal amplitude');

% 3. Time-domain analysis.

% (a) What is the average value of the signal? Use the mean command
% to validate your observation.

mean(instrumentSound)

% (b) Estimate the principal frequency of the note being played from
% the time-domain plot. Zoom the time-domain plot to 1.5s to 1.6s.
% You can do this using the MATLAB command

xlim( [1.5 1.6] );

% or the Zoom tool which is under the Tools menu in the figure window.
% To estimate the principal frequency, count the number of periods,
% estimate the fundamental period by dividing the duration of time
% by the number of periods, and invert the estimate of the fundamental
% period.  Use the Data Tips tool to click on the start of the first period
% and the end of the last period to estimate the duration of time.

ffundest = 26 / 0.1

%  (c) How does your estimate of the principal frequency compare with
%  the principal frequency of a ‘C4’ note?

% C4 = 261.625 Hz
% Estimate gives 260 Hz
% Which is 0.6% relative error ((261.625 - 260)/261.625

% (d) What is the sampling rate of the original recording the
% The McGill University Master Samples Links to an external site.collection of audio CD recordings?
% What is the sampling rate of recording in the file ‘violin-C4.wav’?
% What’s the ratio between these sampling rates?

% The original recording was sampled using a sample rate of 44100 Hz
% The recording was resampled to have a sampling rate of 11025 Hz

% 4. Time-frequency analysis.

blockSize = 1024; % Slide 4-12
overlap = 512;
spectrogram(instrumentSound, blockSize, overlap, blockSize, fs, 'yaxis');

% What is the frequency resolution of the spectrogram command?

fs / blockSize 

% What is the value of the principal frequency of the signal?

% 258 Hz