如何在播放时绘制 wav 文件

How to plot a wav file while it is playing

你如何在播放 wavfile 时在 matlab 上绘制 wave 文件。我想绘制振幅与时间的关系图。我已尝试使用以下代码尝试此操作:

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

使用 sound 你没有真正的机会做到这一点,但使用 audioplayer class 你可以做到这一点:

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

使用自动移动到一边的绘图可能会进一步提高此绘图的质量,使用 timerFcn 仅用于重新同步。