% Tune-Up #3 Solutions by Prof. Brian Evans.  Sept. 12, 2023.

% 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.

% We will solve the questions in Section 2 of the mini-project #1
% https://users.ece.utexas.edu/~bevans/courses/signals/homework/miniproject1.pdfLinks to an external site.

% 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/Links to an external site.
% 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');
% (a) Submit the time-domain plot of the recording (above)

% (b) What is the average value of the signal?
% Answer: Zero, or close to zero.
% Use the mean command to validate your observation.
mean(instrumentSound)

% (c) 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] )
figure;
plot(t, instrumentSound);
xlabel('Time [s]');
ylabel('Signal amplitude');
xlim( [1.5 1.6] )

% 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.
% Fund period from the zoomed plot: 26 peaks -> 25 periods
fundPeriod = (1.599 - 1.50295) / 25;
fundFrequency = 1 / fundPeriod
C4fundFrequency = 261.63
fundFrequencyRelErr = (C4fundFrequency - fundFrequency) / C4fundFrequency

% (d) What is the sampling rate of the original recording on the
% McGill University Master Samples Links 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?
% Sampling rates
audioCDsamplingRate = 44100
violinC4samplingRate = fs
samplingRateRatio = audioCDsamplingRate / violinC4samplingRate
