function [Fs, xr, bits, x] = encode(x, filename, start, stop, quantType, outFileBefore, outFileAfter) % use this sampling frequency and bits if not specified Fs = 44100; bits = 16; totalBits = 0; % if user gave a filename, read the file in if ~isempty(filename) [xFile,Fs,bits] = wavread(filename); xFile = transpose(xFile); if (start == -1) x = xFile; else x = xFile(start:stop); end end % build array of frequencies FFTLength = 512; f=[1:FFTLength/2]*(Fs/FFTLength); % set number of filters M = 32; % set filter length; L = 2*M; w = zeros(1,L); h = zeros(M,L); g = zeros(M,L); xr = zeros(1,length(x)); % define the low-pass window for n = 1:L w(1,n) = sin((pi/(2*M))*(n - 1 + 0.5)); end for k = 1:M %compute analysis and synthesis filters for n = 1:L h(k,n) = w(n)*sqrt(2/M)*cos(((2*(n - 1) + M + 1) * (2*(k - 1) + 1) * pi)/(4*M)); g(k,L - n + 1) = h(k,n); end end start = 1; count = 1; % window the signal into FFTLength frames while (start <= (length(x) - FFTLength + 1)) count count = count + 1; % window the input xF = x(start:start + FFTLength - 1); %find the masking threshold for the window thres = findThreshold(xF, FFTLength, f, bits); % send the signal into the filter banks [filtered, totalBits] = filterBanks8(xF,'',0,0, h, g, Fs, bits, f, thres, FFTLength, totalBits, quantType); % build up final reconstructed signal xr(start:start + FFTLength - 1) = xr(start:start + FFTLength - 1) + filtered; start = start + FFTLength - FFTLength/16; end figure; %plot original and reconstructed signals subplot(2,1,1),plot(x,'b'); subplot(2,1,2),plot(xr,'r'); figure; %plot FFTs of original and reconstructed signals subplot(2,1,1),plot(abs(fft(x)),'b'); subplot(2,1,2),plot(abs(fft(xr)),'r'); figure; % plot FFT error plot(abs(fft(x)) - abs(fft(xr))); if ~isempty(outFileBefore) outFileBefore = strcat('demo\', outFileBefore); end if ~isempty(outFileAfter) outFileAfter = strcat('demo\', outFileAfter); end % calculate compression ratio bitsBefore = length(x) * bits bitsAfter = totalBits percent = bitsAfter / bitsBefore * 100 % write wave files to disk if ~isempty(outFileBefore) wavwrite(x, Fs, bits, outFileBefore); end if ~isempty(outFileAfter) wavwrite(xr, Fs, bits, outFileAfter); fid = fopen(strcat(outFileAfter, '.txt'),'w'); fprintf(fid, 'Before: %d\nAfter: %d\nPercent: %f', bitsBefore, bitsAfter, percent); fclose(fid); end