MATLAB: How to go about using startBackground to get live microphone data, and process that data live

begginerdatahelpMATLABmicrophoneSignal Processing Toolbox

Basically I want to get microphone data, put it through the B1 = bandpower(data,fs,freqrange1) method, and then output the result of the method. And I want it to do this constantly. How do I go about doing this? I've tried various documentation, but they don't explain well how to use the listener to get data into a variable. Here is what I have so far:
fs = 41000;
d = daq.getDevices;
dev = d(2);
s = daq.createSession('directsound');
ch = addAudioInputChannel(s, dev.ID, 1);
s.IsContinuous = true;
lh = addlistener(s,'DataAvailable', @(src,event) expr); //This is where I am getting stuck. How do I make this so it feeds the data it recieves from the mic into a variable called data that I can then use to input into the bandpower method.
freqrange1 = [20,60];
freqrange2 = [60,100];
freqrange3 = [100,500];
freqrange4 = [500,1000];
freqrange5 = [1000,1500];
freqrange6 = [1500,2000];
freqrange7 = [2000,2750];
data = startBackground(s);
while s.IsContinous
B1 = bandpower(data,fs,freqrange1);
B2 = bandpower(data,fs,freqrange2);
B3 = bandpower(data,fs,freqrange3);
B4 = bandpower(data,fs,freqrange4);
B5 = bandpower(data,fs,freqrange5);
B6 = bandpower(data,fs,freqrange6);
B7 = bandpower(data,fs,freqrange7);
end

Best Answer

"How do I make this so it feeds the data it recieves from the mic into a variable called data that I can then use to input into the bandpower method."
You do not do that.
When you use background operations, have you to get rid of the idea that the background operation is going to return data that you can store into a variable and then proceed to analyze. Instead you need to make the function you designate as the listener do the work.
Look at the first example for startBackground:
s = daq.createSession('ni');
addAnalogInputChannel(s,'cDAQ1Mod1','ai0','Voltage');
lh = addlistener(s,'DataAvailable',@plotData);
function plotData(src,event)
plot(event.TimeStamps,event.Data)
end
each time that data is available, the function plotData will be invoked with two arguments. The data is available in the Data field of the second argument.
For example you could code
function do_the_thing
[...]
lh = addlistener(s,'DataAvailable', @(src, event) analyze_bandpower(event.Data));
startBackground(s);
function analyze_bandpower(data) %nested so can use the shared variables freqrange*
B1 = bandpower(data,fs,freqrange1);
B2 = bandpower(data,fs,freqrange2);
B3 = bandpower(data,fs,freqrange3);
B4 = bandpower(data,fs,freqrange4);
B5 = bandpower(data,fs,freqrange5);
B6 = bandpower(data,fs,freqrange6);
B7 = bandpower(data,fs,freqrange7);
end
end
Related Question