close all; clear all;
[audio, Fs] = audioread('Immigrant Song.mp3');
x_OAM = audio;
x_OSM = audio;
player0 = audioplayer(x_OAM, Fs);
% play(player0)
% stop(player0)
%% Filter
b = [0.2];
a = [1 -0.8];
[h,t] = impz(b,a);
h = [h h];
% concatenação do vetor - matriz nx2 - n é a quantidade de linhas nem precisa
% transformar o filtro em matriz, basta convoluir com -> h no lugar de h(:,1) ou h(:,2)
%% Linear Convolution
lc1 = conv(x_OAM(:,1), h(:,1));
lc2 = conv(x_OAM(:,2), h(:,2));
lc = [lc1 lc2];
%%
L = 10000;
N1 = length(x_OAM);
M = length(h);
h = [h; zeros(L-1, 2)];
H1 = fft(h(:,1),L+M-1);
H2 = fft(h(:,2),L+M-1);
H = [H1 H2];
%% Overlap and Add
x_OAM = [x_OAM; zeros(mod(-N1,L), 2)]; %OAM - Overlap-add Method
N2 = length(x_OAM);
S = N2/L;
idx = 1:L;
X_OAM = [zeros(M-1,2)];
for stage = 1:S
% Selecting sequence to process
xm = [x_OAM(idx,:); zeros(M-1, 2)];
X1 = fft(xm(:,:), L+M-1);
Y = X1 .* H;
Y = ifft(Y);
% Samples Added in every stage
Z1 = X_OAM((length(X_OAM)-M+2):length(X_OAM),1) + Y(1:M-1,1); % Channel 1
Z2 = X_OAM((length(X_OAM)-M+2):length(X_OAM),2) + Y(1:M-1,2); % Channel 2
Z = [Z1 Z2];
X_OAM = [X_OAM(1:(stage-1)*L,:); Z(:,:); Y(M:M+L-1, :)];
idx = stage*L+1:(stage+1)*L;
end
ii = 1 : N1+M-1;
X_OAM = X_OAM(ii,:);
similarity_OAM = corrcoef(X_OAM, lc)
%% Overlap and Save
x_OSM = [x_OSM; zeros(mod(-N1,L), 2); zeros(L, 2)];
N2 = length(x_OSM);
S = N2/L;
idx0 = 1:L;
xm = x_OSM(idx0, :); % For first stage Special Case
x1 = [zeros(M-1, 2); xm]; % zeros appeded at Start point
X_OSM = [];
for stage=1:S
X1 = fft(x1(:,:), L+M-1);
Y = X1 .* H;
Y = ifft(Y);
Y = Y(M:M+L-1, :); %Discarding Samples
X_OSM = [X_OSM; Y];
idx1 = ((stage*L)-M+2):((stage+1)*L); % Selecting Sequence to process
if idx1(L+M-1) <= N2
x1 = x_OSM(idx1, :);
end
end
jj = 1:N1+M-1;
X_OSM = X_OSM(jj,:);
similarity_OSM = corrcoef(X_OSM,lc)
%% Play Music
player0 = audioplayer(X_OAM, Fs);
%play(player0)
%stop(player0)
player1 = audioplayer(X_OSM, Fs);
%play(player1)
%stop(player1)
%% Plots
figure()
subplot(3,1,1); plot(lc);
title('Convolution Using conv() function')
xlabel('n'); ylabel('y(n)');
subplot(3,1,2); plot(X_OAM);
title('Convolution Using Overlap Add Method')
xlabel('n'); ylabel('y(n)');
subplot(3,1,3); plot(X_OSM);
title('Convolution Using Overlap Save Method')
xlabel('n'); ylabel('y(n)');