% Demonstration of LMS algorithm for noise cancellation.
% Rich Kozick, Spring 1997
% Rob Frohne's modifications for Aircraft Noise Cancellation.
% modifications for Macintosh 2000. (commented out here)
% Rob Frohne's modifications for Linux.
% Aircraft noise cancellation simulation.
% Desired signal
clear all
Totaltime=3;
system("aoss espeak 'Hit a key and speak the signal.'");
Fs=8000; %sample rate.
st=record(Totaltime,Fs);
s = st';
Ls = length(s);
% Interference + random noise
system("aoss espeak 'Hit a key and make the noise!'");
%pause();
nt = record(Totaltime, Fs);
n = nt';
%Sign = 0.01;
%Dn=20; % Delay of the noise that appears in y.
%n = n(1:Ls) + Sign*randn(Ls,1);
%an = [0 .01 -.5 1 -.5 .1 .01 0];
%bn = 4*[0 0 0 0 0 0 0 0 0 0 0 0 0 0 .5 1 .5];
bn=rand(1,20);
an = [1];
%sys = tf(an,bn,1/Fs);
%bode(sys);
%figure(1);
nf = filter(bn,an,n);
%nf = [nf(Dn:(Ls)); zeros(Dn-1,1)] + Sign*randn(Ls,1);
y = s + nf;
%Sigx = 0.01;
%ax = [1]; % bx and ax are filtering on n to produce x
%bx = [0 0 0 .1 1 .1];
%Dx = 1; % Delay of n that appears in x
%x = filter(bx, ax, n);%x = [x(Dx:(Ls)); zeros(Dx-1,1)] + Sigx*randn(Ls,1);
%x = x + Sigx*randn(1,Ls);
system("aoss espeak 'Here is the noisy signal.'");
soundsc(y,Fs);
N = 20; % Length of adaptive filter
% LMS algorithm for adaptive noise cancellation
h = zeros(N,1);
%mu = 1/(10*N*var(n));
mu = .05;
for k=N:Ls
xk = n(k:-1:(k-N+1));
nhat(k) = h'*xk';
e(k) = - y(k) + nhat(k);
h = h - mu*e(k)*xk'/(xk*xk'); % For the previous line.
end
% The signal estimate is in the vector e
%speak('Here is the cleaned signal.');
system("aoss espeak 'Here is the cleaned signal.'");
soundsc(e(1,6000:end),Fs);
%playaudio(e); (For Linux without octave-forge.)