%% listing 5.14
% in the following example we generate
% a band-pass filtered noise
sr = 44100; % sample rate in Hz
d = 1; % duration of the noise in seconds

% generate a uniformly distributed white noise
% and normalize its amplitude

whitenoise = randn(sr*d, 1);
whitenoise = whitenoise/max(abs(whitenoise));
wnoise_in_freq = fft(whitenoise);

% Calculate the band-pass filter
lf = 2000; % lowest freq. of the cutoff freq.
hf = 6000; % highwest freq. of the cutoff freq.
lf_insamples = lf * d;
hf_insamples = hf * d;
filter = zeros(length(wnoise_in_freq), 1);
filter(lf_insamples:hf_insamples) = 1;
filter(end-hf_insamples:end-lf_insamples) = 1;

% Filter the noise
filtnoise_in_freq = filter .* wnoise_in_freq;

% Obtain the filtered noise in time
filterednoise = ifft(filtnoise_in_freq);
filterednoise = real(filterednoise);

%Plot results
figure;
subplot(3, 2, 1);
plot(whitenoise);
xlabel('time (sec)'), ylabel('amplitude');
subplot(3, 2, 2);
plot(20*log10(abs(wnoise_in_freq(1:22050))));
xlabel('frequency Hz'), ylabel('dB');
subplot(3, 2, 3:4);
plot(1:22050,filter(1:22050));
xlabel('frequency (Hz)'), ylabel('dB')
subplot(3, 2, 5);
plot(20*log10(abs(filtnoise_in_freq(1:22050))));
xlabel('frequency (Hz)'), ylabel('dB')
subplot(3, 2, 6);
plot(filterednoise)
xlabel('time (sec)'), ylabel('amplitude');

%% play
if ispc
    wavplay(whitenoise, 'sync');
    wavplay(filterednoise, sr);
elseif ismac
    sound(whitenoise, sr);
    sound(filterednoise, sr);
end