%% Upsample an Audio Signal Using dsp.FarrowRateConverter
% Note:  If you are using R2016a or an earlier release, replace each call to the object with the equivalent step syntax. For example, obj(x) becomes step(obj,x).
% Note: The dsp.AudioFileReader and dsp.AudioFileWriter System objects are not supported in MATLAB Online.
% Create a dsp.FarrowRateConverter System object™ to convert an audio signal from 44.1 kHz to 96 kHz. Set the polynomial order for the filter.

fs1 = 44.1e3;
fs2 = 96e3;
LagrangeOrder = 2; % 1 = linear interpolation
frc = dsp.FarrowRateConverter('InputSampleRate',fs1,...
                              'OutputSampleRate',fs2,...
                              'PolynomialOrder',LagrangeOrder);
ar = dsp.AudioFileReader('guitar10min.ogg','SamplesPerFrame',14700);
aw = dsp.AudioFileWriter('guitar10min_96kHz.wav','SampleRate',fs2);

%
% Check the resulting interpolation and decimation factors.

[interp,decim] = getRateChangeFactors(frc)

%
% Display the polynomial that the object uses to fit the input samples.

coeffs = getPolynomialCoefficients(frc)

%
% Convert 100 frames of the audio signal. Write the result to a file.

for n = 1:1:100
   x = ar();  
   y = frc(x);
   aw(y);
end

%
% Release the AudioFileWriter System object™ to complete creation of the output file.

release(aw)
release(ar)

%
% Plot the input and output signals of the 100th frame of data. Delay the input to compensate for the latency of the filter.

t1 = 0:1/fs1:1/30-1/fs1;
t2 = 0:1/fs2:1/30-1/fs2;

delay = ceil((LagrangeOrder+1)/2)/fs1;
el1 = 1:length(t1)-delay;
el2 = 1:length(t2);
el2(1:delay) = [];

figure

subplot(2,1,1)
plot(t1(1:length(el1)),x(el1,1))
hold on
plot(t1(1:length(el1)),x(el1,2))
xlabel('Time (s)')
title('Input Channels')

subplot(2,1,2)
plot(t2(1:length(el2)),y(el2,1))
hold on
plot(t2(1:length(el2)),y(el2,2))
xlabel('Time (s)')
title('Output Channels')

%
% Zoom in to see the difference in sample rates.

figure

subplot(2,1,1)
plot(t1(1:length(el1)),x(el1,1),'o-')
hold on
plot(t2(1:length(el2)),y(el2,1),'d--')
xlim([0.0104 0.0107])
title('First Channel')
xlabel('Time (s)')
legend('Input','Output')

subplot(2,1,2)
plot(t1(1:length(el1)),x(el1,2),'o-')
hold on
plot(t2(1:length(el2)),y(el2,2),'d--')
xlim([0.0104 0.0107])
xlabel('Time (s)')
title('Second Channel')
legend('Input','Output')