Matlab Project: How can create a .wav bar based spectrogram in matlab?
Show older comments
How can I create a bar based spectrogram that updates as a .wav file is playing. This is commonly found in music players. Here is an example below:

I am able to display a amplitude/frequency graph that updates as the .wav file is being played using this code below:
function syncPlayerDemo()
%some example music
%set up audio player
%player = audioread('test.wav');
[y,Fs] = audioread('test.wav');
player = audioplayer(y, Fs);
[samples,channels]=size(y);
%calculate timeline
t=linspace(0,1/Fs*(samples-1),samples);
%initialize full plot, update will only move the visible area using xlim
h=plot(t,y);
%set up callback to update every <TimerPeriod> s
player.TimerFcn=@timerFcn;
player.TimerPeriod=0.1;
player.playblocking()
end
function timerFcn(source,data)
%an area of length <area> s will be visible
area=1;
position=(source.CurrentSample-1)/source.SampleRate;
%move visible area, current position is in the center
set(gca,'XLim',[position-area/2,position+area/2]);
%used a waitbar for testing, might be commented in
%waitbar(source.CurrentSample/source.TotalSamples);
end
Which results in an updating graph:

%
Answers (1)
Antonio Monteiro
on 18 Jan 2021
0 votes
Hey I like the code!
ahhhh use "barh" instead of "plot" but you have to use the absolute values of t and y and change the Lim to 'YLim'
or use "bar" instead of "plot" and use the absolute values of t and y and change the to 'XLim'
hopefully this helps!
function syncPlayerDemo()
%some example music
%set up audio player
%player = audioread('test.wav');
[y,Fs] = audioread('squid ethics x jhfly.wav'); %% my fav song :)
player = audioplayer(y, Fs);
[samples,channels]=size(y);
%calculate timeline
t=linspace(0,1/Fs*(samples-1),samples);
%initialize full plot, update will only move the visible area using xlim
h=bar(abs(t),abs(y));
%set up callback to update every <TimerPeriod> s
player.TimerFcn=@timerFcn;
player.TimerPeriod=0.1;
% plays from beginning; does not return until playback completes.
player.playblocking()
end
function timerFcn(source,data)
%an area of length <area> s will be visible
area=1;
position=(source.CurrentSample-1)/source.SampleRate;
%move visible area, current position is in the center
set(gca,'XLim',[position-area/2,position+area/2]);
%used a waitbar for testing, might be commented in
%waitbar(source.CurrentSample/source.TotalSamples);
end

Categories
Find more on Audio and Video Data in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!