3

I am trying to find a way to create a graph that shows an audio wave and its time-frequency data (time on x-axis, wave energy and frequency data on y-axis). I have this code that does it on two separate plots:

[audio, fs] = wavread('audio.wav');

subplot(211)
spectrogram(audio,256,200,256,fs,'yaxis')

subplot(212)
wavEnergy=audio(:,1);
time=(1/fs)*length(wavEnergy);
t=linspace(0,time,length(wavEnergy));
plot(t,wavEnergy);

and now I need help with 2 things.

First, how do I get the spectrogram time to be in terms of seconds? Right now it graphs with an x-range of 0-340 (labeled 'time') and I know the clip is about 40s long (the other plot properly displays this).

Second, how do I plot them together? I know I can get a matrix from spectrogram but which array do I get from that matrix and how do I convert its timeframe to seconds?

EDIT:

First problem solved, but the graphs are still doing something strange - they both output about 40s of data, but the ranges of the graphs and the offsets of the data are different. The spectrogram goes from 0s-40s but the first .5s shows no data, and the wave plot goes from 0s-45s and the last 5s shows no data. How can I get the ranges and offsets to be the same?

EDIT 2:

I just needed to use axis tight; on both subplots

Cbas
  • 6,003
  • 11
  • 56
  • 87
  • Aligning these two plots on the same time-base relies on determining the sampling frequency of your data. Based on the parameter you are passing to spectrogram, the sampling frequency is 1000 Hz. Based on your definition of `time = (1/8000)*length(wavEnergy)`, the sampling frequency is 8000 Hz. These are not consistent. To get the audio sampling frequency from your wav file you can use `[audio, fs] = wavread('audio.wav')`. Also, I think your subplot command should be `subplot(2,1,1)` rather than `subplot(211)`. – cjh Sep 22 '12 at 21:41
  • Thanks for explaining. I was able to get the time range correct, but I ran into a new problem as well – Cbas Sep 22 '12 at 21:53
  • nvm. You basically answered my question - if you turn it into an answer, I'll accept it. – Cbas Sep 23 '12 at 02:25
  • glad I could help! If you are needing to plot a lot of spectra for research purposes then you may want to look into MATLAB toolboxes such as [Fieldtrip](http://fieldtrip.fcdonders.nl/) or [Chronux](http://www.chronux.org) which can generate more precise spectral estimates along with statistics. – cjh Sep 23 '12 at 13:51

1 Answers1

3

Aligning these two plots on the same time-base relies on determining the sampling frequency of your data. Based on the parameter you are passing to spectrogram, the sampling frequency is 1000 Hz. Based on your definition of time = (1/8000)*length(wavEnergy), the sampling frequency is 8000 Hz. These are not consistent. To get the audio sampling frequency from your wav file you can use [audio, fs] = wavread('audio.wav').

cjh
  • 866
  • 4
  • 16