%% Add Pink Noise to Audio Signal
% Read in an audio file.

[audioIn,fs] = audioread("MainStreetOne-24-96-stereo-63secs.wav");

%
% Create a pink noise signal of the same size and data type as audioIn.

noise = pinknoise(size(audioIn),'like',audioIn);

%
% Add the pink noise to the audio signal and then listen to the first 5 seconds.

noisyMainStreet = noise + audioIn;
sound(noisyMainStreet(1:fs*5,:),fs)

% The pinknoise function generates an approximate -29.5 dB signal level, which is close to the power of the audio signal.

noisePower = sum(noise.^2,1)/size(noise,1);
signalPower = sum(audioIn.^2,1)/size(audioIn,1);
snr = 10*log10(signalPower./noisePower)
noisePowerdB = 10*log10(noisePower)
signalPowerdB = 10*log10(signalPower)

% Mix the input audio with the generated pink noise at an 8 dB SNR.

desiredSNR = 8;
scaleFactor = sqrt(signalPower./(noisePower*(10^(desiredSNR/10))));

noise = noise.*scaleFactor;

%
% Verify the resulting SNR is 8 dB and then listen to the first 5 seconds.

noisePower = sum(noise.^2,1)/size(noise,1);
snr = 10*log10(signalPower./noisePower)

%

noisyMainStreet = noise + audioIn;
sound(noisyMainStreet(1:fs*5,:),fs)

%
%
% Copyright 2019 The MathWorks, Inc.