So I wrote this, basically to update the spectrogram in real time.
function spec(Fs, n_bits, n_channels, update_rate)
%# Initialise default parameters if not supplied
if (~exist('Fs', 'var'))
Fs = 44000;
end
if (~exist('n_bits', 'var'))
n_bits = 16;
end
if (~exist('n_channels', 'var'))
n_channels = 2;
end
if (~exist('update_rate', 'var'))
update_rate = 5;
end
plot_colors = hsv(n_channels);
%# Initialise plots, one above each other in a single figure window
figure;
%# Time Domain plot
hold on
%# Setup the audiorecorder which will acquire data off default soundcard
audio_recorder = audiorecorder(Fs, n_bits, n_channels);
set(audio_recorder, 'TimerFcn', {@audioRecorderTimerCallback, ...
audio_recorder});
set(audio_recorder, 'TimerPeriod', 1/update_rate);
set(audio_recorder, 'BufferLength', 1/update_rate);
%# Start the recorder
record(audio_recorder);
end
function audioRecorderTimerCallback(obj, event, audio_recorder)
Fs = get(obj, 'SampleRate');
num_channels = get(obj, 'NumberOfChannels');
num_bits = get(obj, 'BitsPerSample');
try
if (num_bits == 8)
data_format = 'int8';
elseif (num_bits == 16)
data_format = 'int16';
elseif (num_bits == 32)
data_format = 'double';
else
error('Unsupported sample size of %d bits', num_bits);
end
%# stop the recorder, grab the data, restart the recorder. May miss some data
stop(obj);
data = getaudiodata(obj, data_format);
record(obj);
if (size(data, 2) ~= num_channels)
error('Soundcard does not support acquisition of %d channels', ...
length(num_channels))
end
data_fft = fft(double(data));
specgram(data_fft,512);
catch
%# Stop the recorder and exit
stop(obj)
rethrow(lasterror)
end
drawnow;
end
I always end up with an empty recorder.
I don’t understand why there is this problem, I did record first.
The problem is that the
specfunction doesn’t return anything, so the audio that you’ve recorded is discarded when the function exits.Change the function signature to
One minor style point is that you can set default values for functions much more cleanly with (cue shameless self-promotion) SetDefaultValue.