%% Convert Sample Rate of Audio Signal
% Convert the sample rate of an audio signal from 44.1 kHz (CD quality) to 96 kHz (DVD quality).
% 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.AudioFileWriter System object™ is not supported in MATLAB Online.

fs1 = 44.1e3;
fs2 = 96e3;

SRC = dsp.SampleRateConverter('Bandwidth',40e3,...
    'InputSampleRate',fs1,'OutputSampleRate',fs2);

[L,M] = getRateChangeFactors(SRC);
FrameSize = 10*M;

AR = dsp.AudioFileReader('guitar10min.ogg', ...
    'SamplesPerFrame',FrameSize);
AW = dsp.AudioFileWriter('guitar10min_96k.wav', ...
    'SampleRate',fs2);

%
% Run the system for 15 s. Release all objects.

tic
while toc < 15
    x = AR();
    y = SRC(x);
    AW(y);
end

release(AR);
release(AW);
release(SRC);

%
% Plot the input and output signals. Use a different set of axes for each signal. Shift the output to compensate for the delay introduced by the filter.

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

delay = 114;

el1 = 1:length(t1)-delay;

el2 = 1:length(t2);
el2(1:delay) = [];

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

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')

%
% Zoom in to see the difference in sample rates. Use a different set of axes for each channel.

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.01 0.0103])
title('First channel')

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.01 0.0103])
xlabel('Time (s)')
title('Second channel')

%
% Copyright 2014 The MathWorks, Inc.