%% Sample Rate Conversion
% Sample rate conversion is a process of converting the sample rate of a signal 
% from one sampling rate to another sampling rate. Multistage filters minimize 
% the amount of computation involved in a sample rate conversion. To perform an 
% efficient multistage rate conversion, the |dsp.SampleRateConverter| object:
% 
% # accepts input sample rate and output sample rate as inputs.
% # partitions the design problem into optimal stages.
% # designs all the filters required by the various stages.
% # implements the design.
% 
% The design makes sure that aliasing does not occur in the intermediate 
% steps.
% 
% In this example, change the sample rate of a noisy sine wave signal from 
% an input rate of 192 kHz to an output rate of 44.1 kHz. Initialize a sample 
% rate converter object.

SRC = dsp.SampleRateConverter;
%% 
% Display the filter information.
%%
info(SRC)
%% 
% |SRC| is a three-stage filter: two FIR decimators followed by an FIR rate 
% converter.
% 
% Initialize the sine wave source. The sine wave has two tones: one at 2000 
% Hz and the other at 5000 Hz.
%%
source = dsp.SineWave ('Frequency',[2000 5000],'SampleRate',192000,...
    'SamplesPerFrame',1280);
%% 
% Initialize the spectrum analyzer to see the input and output signals.
%%
Fsin = SRC.InputSampleRate;
Fsout = SRC.OutputSampleRate;
specanainput = dsp.SpectrumAnalyzer('SampleRate',Fsin,...
    'PlotAsTwoSidedSpectrum',false,...
    'ShowLegend',true,'YLimits',[-120 30],...
    'Title','Input signal',...
    'ChannelNames', {'Input'});
specanaoutput = dsp.SpectrumAnalyzer('SampleRate',Fsout,...
    'PlotAsTwoSidedSpectrum',false,...
    'ShowLegend',true,'YLimits',[-120 30],...
    'Title','Rate Converted output',...
    'ChannelNames', {'Rate Converted output'});
%% 
% Stream in the input signal and convert the signal's sample rate.
%%
for Iter = 1 : 5000
    input = sum(source(),2);
    noisyinput = input + (10^-5)*randn(1280,1);
    output = SRC(noisyinput);
    specanainput(noisyinput);
    specanaoutput(output);
end
%% 
% The spectrum shown is one-sided in the range [0 Fs/2]. For the spectrum 
% analyzer showing the input, Fs/2 is 192000/2. For the spectrum analyzer showing 
% the output, Fs/2 is 44100/2. Hence, the sample rate of the signal changed from 
% 192 kHz to 44.1 kHz.

%% 
% Copyright 2012 The MathWorks, Inc.