% Speech Quantization
% A speech signal is quantized to a specified number of levels.
% The results are played through the sound card, and quantization
% error and signal spectra are computed.

% Initialize
close all
clear
%-----------------------------
% Parameters
Nbits=5; 
nlevels=2^Nbits;
%-----------------------------
%data=getspeech('erf1s1t0.wav');
%Fs=12500;
data=load('erf1s1t0');
Fs=8192;

plot(data)
%end1=input('end1?');
%end2=input('end2?');
%datar=data(end1:end2);
datar=data;

mind=min(datar); maxd=max(datar); 
amax=max(maxd,abs(mind));
range=maxd-mind; 
% determine number of quantization levels/bits for input ascii-type data
nlevels_orig=range+1
nbits_orig=ceil(log(nlevels_orig)/log(2))
% quantize data to Nbits
qdelta=range/(nlevels-1);
qdata = qdelta*round((datar-mind)/qdelta);
%qdata=-amax+qdelta*round((datar+amax)/qdelta);
qdata=qdata-mean(qdata);

msg=sprintf('Original speech data with %d bits per sample...',nbits_orig);
disp(msg); pause;
soundsc(datar,Fs);
msg=sprintf('Quantized speech with %d bits per sample...',Nbits);
disp(msg); pause;
soundsc(qdata,Fs);

subplot(211)
plot(datar)
msg=sprintf('Original speech data with %d bits per sample',nbits_orig);
title(msg)
subplot(212)
plot(qdata)
msg=sprintf('Quantized speech with %d bits per sample',Nbits);
title(msg);
disp('Quantization error plotted next'); pause;
clf
plot(qdata-datar)
title('quantization error')
dlength=length(datar);
axis([1 dlength mind maxd])
domega=2*pi/8192;
omega=-pi:domega:pi-domega;
daf1=abs(fftshift(fft(datar,8192)));
disp('DTFTs plotted next'); pause;
clf
subplot(211)
plot(omega,daf1)
axis([-pi pi 0 max(daf1)]);
title('Magnitude of DTFT of original utterance');
xlabel('omega (radians/s)');
subplot(212)
qdaf=abs(fftshift(fft(qdata,8192)));
plot(omega,qdaf)
axis([-pi pi 0 max(qdaf)]);
title('Magnitude of DTFT of quantized waveform');
xlabel('omega (radians/s)');

