Techno04335
Techno04335

Reputation: 1445

How to plot a wav file while it is playing

How do you go about plotting a wave file on matlab while the wavfile is playing. I would like to plot amplitude vs time. I have tried to attempt this with my following code below:

[y,Fs] = audioread('test.wav');
sound(y,Fs);
clear y Fs

Upvotes: 3

Views: 774

Answers (1)

Daniel
Daniel

Reputation: 36710

Using sound you don't have a real chance to do this, but using the audioplayer class you can do this:

function syncPlayerDemo()
%some example music
load handel;
%set up audio player
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

The quality of this plot might be further increased using a plot which automatically moves to the side, using the timerFcn only to resynchronize.

Upvotes: 2

Related Questions