运行此MATLAB代码时,为什么记录器为空?

时间:2011-07-13 16:12:04

标签: 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_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

我总是以空录音机结束。

我不明白为什么会出现这个问题,我先做了记录。

2 个答案:

答案 0 :(得分:0)

问题是spec函数没有返回任何内容,因此当函数退出时,您录制的音频将被丢弃。

将功能签名更改为

function audio_recorder = spec(Fs, n_bits, n_channels, update_rate)

一个小的风格点是你可以更加干净地设置函数的默认值(cue无耻的自我提升)SetDefaultValue

答案 1 :(得分:0)

另一个技巧是在SPEC函数的末尾添加它:

uiwait
set(audio_recorder, 'StopFcn','uiresume');