为什么运行这个MATLAB代码时记录器是空的?
所以我写这篇文章,基本上是为了实时更新光谱图为什么运行这个MATLAB代码时记录器是空的?,matlab,Matlab,所以我写这篇文章,基本上是为了实时更新光谱图 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_chan
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
我的录音机总是空的
我不明白为什么会出现这个问题,我确实是先录制的。问题是spec函数没有返回任何内容,因此当函数退出时,您录制的音频将被丢弃
将函数签名更改为
function audio_recorder = spec(Fs, n_bits, n_channels, update_rate)
一个次要的风格点是,您可以通过cue无耻的自我提升更清晰地设置函数的默认值。另一个技巧是在SPEC函数末尾添加以下内容:
uiwait
set(audio_recorder, 'StopFcn','uiresume');
@@@@非常感谢,设置默认值,我从互联网上的一个例子中学到了这一点,感谢更简单的方法:你知道如何提高SPC图显示的质量吗?我的意思是,当它的绘图时,它看起来几乎像像素。这个代码对我很有帮助。一个有用的修改:不要在回调中停止和启动记录器。我的意思是删除stopobj和recordobj并简单地读取数据,注意数据长度将不断增加。这将防止丢失某些数据。注意stop命令停止记录到缓冲区,record命令使用新的缓冲区,缓冲区将随着我上面给出的修改而继续增长。