main content

acquire continuous audio data -凯发k8网页登录

this example shows how to set up a continuous audio acquisition using a microphone.

create a dataacquisition

create a dataacquisition with directsound as the vendor and add an audio input channel to it using addinput.

dq = daq("directsound");
addinput(dq,"audio0",1,"audio");

set up the fft plot

hf = figure;
hp = plot(zeros(1000,1));
t = title('discrete fft plot');
xlabel('frequency (hz)')
ylabel('|y(f)|')
grid on;

set scansavailablefcn

update the figure with the fft of the live input signal by setting the scansavailablefcn.

dq.scansavailablefcn = @(src, evt) continuousfft(src, hp);

start acquisition

the figure updates, for 10 seconds, as the microphone is used.

start(dq,"duration",seconds(10));
figure(hf);

function continuousfft(daqhandle, plothandle)
% calculate fft(data) and update plot with it.
data = read(daqhandle, daqhandle.scansavailablefcncount, "outputformat", "matrix");
fs = daqhandle.rate;
lengthofdata = length(data);
% next closest power of 2 to the length
nextpoweroftwo = 2 ^ nextpow2(lengthofdata);
plotscalefactor = 4;
% plot is symmetric about n/2
plotrange = nextpoweroftwo / 2; 
plotrange = floor(plotrange / plotscalefactor);
ydft = fft(data, nextpoweroftwo); 
h = ydft(1:plotrange);
abs_h = abs(h);
% frequency range
freqrange = (0:nextpoweroftwo-1) * (fs / nextpoweroftwo);
% only plot up to n/2 (as other half is the mirror image)
gfreq = freqrange(1:plotrange);  
% update the plot
set(plothandle, 'ydata', abs_h, 'xdata', gfreq);
drawnow
end
网站地图