%% Add Pink Noise at 0 dB SNR
% Note:  If you are using R2016a or an earlier release, replace each call to the object with the equivalent step syntax. For example, obj(x) becomes step(obj,x).
% Note: The audioDeviceWriter System object™ is not supported in MATLAB Online.
% This example shows how to stream in an audio file and add pink noise at a 0 dB signal-to-noise ratio (SNR). The example reads in frames of an audio file 1024 samples in length, measures the root mean square (RMS) value of the audio frame, and adds pink noise with the same RMS value as the audio frame.
% Set up the System objects. Set 'SamplesPerFrame' for both the file reader and the colored noise generator to 1024 samples. Set Color to 'pink' to generate pink noise with a 1/|f| power spectral density.

N = 1024;
afr = dsp.AudioFileReader('Filename','speech_dft.mp3','SamplesPerFrame',N);
adw = audioDeviceWriter('SampleRate',afr.SampleRate);
cn = dsp.ColoredNoise('pink','SamplesPerFrame',N);

% Stream the audio file in 1024 samples at a time. Measure the signal RMS value for each frame, generate a frame of pink noise equal in length, and scale the RMS value of the pink noise to match the signal. Add the scaled noise to the signal and play the output.

while ~isDone(afr)
    audio = afr();
    speechRMS = rms(audio);
    noise = cn();
    noiseRMS = rms(noise);
    noise = noise*(speechRMS/noiseRMS);
    sigPlusNoise = audio+noise;
    adw(sigPlusNoise);   
end
release(afr);            
release(adw);

% Copyright 2014 The MathWorks, Inc.