%% Plot Spectral Entropy of Speech Signal
% Plot the spectral entropy of a speech signal and compare it to the original signal. Visualize the spectral entropy on a color map by first creating a power spectrogram, and then taking the spectral entropy of frequency bins within the bandwidth of speech.
%
% Load the data, x, which contains a two-channel recording of the word "Hello" embedded by low-level white noise. x consists of two columns representing the two channels. Use only the first channel.
% Define the sample rate and the time vector. Augment the first channel of x with white noise to achieve a signal-to-noise ratio of about 5 to 1.

load Hello x
fs = 44100;
t = 1/fs*(0:length(x)-1);
x1 = x(:,1) + 0.01*randn(length(x),1);

% Find the spectral entropy. Visualize the data for the original signal and for the spectral entropy.

[se,te] = pentropy(x1,fs);

subplot(2,1,1)
plot(t,x1)
ylabel('Speech Signal')
xlabel('Time')

subplot(2,1,2)
plot(te,se)
ylabel('Spectral Entropy')
xlabel('Time')

% The spectral entropy drops when "Hello" is spoken. This is because the signal spectrum has changed from almost a constant (white noise) to the distribution of a human voice. The human-voice distribution contains more information and has lower spectral entropy.
% Compute the power spectrogram p of the original signal, returning frequency vector fp and time vector tp as well. For this case, specifying a frequency resolution of 20 Hz provides acceptable clarity in the result.

[p,fp,tp] = pspectrum(x1,fs,'FrequencyResolution',20,'spectrogram');

% The frequency vector of the power spectrogram goes to 22,050 Hz, but the range of interest with respect to speech is limited to the telephony bandwidth of 300–3400 Hz. Divide the data into five frequency bins by defining start and end points, and compute the spectral entropy for each bin.

flow = [300 628 1064 1634 2394];
fup = [627 1060 1633 2393 3400];
 
se2 = zeros(length(flow),size(p,2));
for i = 1:length(flow)
    se2(i,:) = pentropy(p,fp,tp,'FrequencyLimits',[flow(i) fup(i)]);
end

% Visualize the data in a color map that shows ascending frequency bins, and compare with the original signal.

subplot(2,1,1)
plot(t,x1)
xlabel('Time (seconds)')
ylabel('Speech Signal')

subplot(2,1,2)
imagesc(tp,[],flip(se2))    % Flip se2 so its plot corresponds to the ascending frequency bins.
h = colorbar(gca,'NorthOutside');
ylabel(h,'Spectral Entropy')
yticks(1:5)
set(gca,'YTickLabel',num2str((5:-1:1).')) % Label the ticks for the ascending bins.
xlabel('Time (seconds)')
ylabel('Frequency Bin')

% Copyright 2012 The MathWorks, Inc.