function out = ditherAndNoiseShape2(in) %The in vector is a list of audio samples %The values are assumed to be between -1 and 1 %Out is the audio samples at a reduced 4-bit %bit depth, dithered and noise shaped. %Out is also on a scale of -1 to 1. N = length(in); c1=1; rnd = ((rand(N,1)+rand(N,1)) * 0.125) - 0.125; %Since we're in 4 bits, we'd go from -8 to 7, so on a scale of -1 to 1, 1 %becomes .125. %This scales the random numbers to be between -.125 and .125. %We handle the randomizing outside of the for loop for speed. in = in+rnd; %dithering outside of for loop for speed for(i=2:N) in(i) = in(i) + c1*(in(i-1) - ((floor(in(i-1)*8))/8)); end %Now we noise shape. Done in one command so the for loop will go much more %quickly. out = (floor(in.*8))./8; %And now we quantize, outside of for loop for speed. %clip upper limit to .875; could be exceeded due to noise shaping outoverflow = (out > (ones(size(out))*0.876)); % > gives a vector result outoverflow = outoverflow .* (out - 0.875); out = out - outoverflow; %clip lower limit to -1; could be exceeded due to noise shaping outunderflow = (out < (ones(size(out))*(-1.001))); % < gives a vector result outunderflow = outunderflow .* (out + 1); out = out - outunderflow; %transpose to get it in the right shape