Realtime audio input
Updated 22 Jul 2011
I explored different options for realtime audio input (see below for a summary) before having to settling for this option. Unfortunately this solution requires Windows and the Data Acquisition toolbox. I hope to be able to report at some point that this function has been superceded by something more generally useful, so please let me know if you come across something better.
PortAudio (http://www.portaudio.com/): seem to be the workhorse of audio input, but it's in C++, not Matlab code
PlayRec.m (http://www.playrec.co.uk/): An adaptation of PortAudio for Matlab. However, support seems to have ended around 2008, and I know several people who have spent many hours failing to compile it for more recent operating systems and/or Matlab versions.
PsychPortAudio (http://docs.psychtoolbox.org/PsychPortAudio): This may be the best option, although it requires PsychToolbox, which can be challenging to install itself. Can anyone confirm that PsychPortAudio works for realtime audio input?
In the meantime, the detailed function of tgrabaudio.m is described in its help section, copied below for convenience:
1/ Initialisation (mandatory)
tgrabaudio('start', [fs, [maxduration]])
fs = the sample-rate [default = 44100]
maxduration = the maximum delay (in seconds) that is considered an
acceptable build-up of audio samples. If this buffer is
exceeded during auditory capture, an error will be generated.
2/ Audio capture
N = the number of samples to be "grabbed".
wave = by default, stereo input [hard-wired: search the code for "addchannel" to adapt for mono input]
3/ Tidying up (mandatory)
This clears the persistent variables and stops the background audio
input. Careful, if this step is omitted, Matlab is likely to crash or
behave strangely the next time tgrabaudio is run. NB if a program that
uses tgrabaudio crashes before calling tgrabaudio('stop'), don't forget
to call tgrabaudio('stop') as soon as possible (either manually or using
Matlab's try...catch keywords).
The following code shows how to use tgrabaudio to input sound in
realtime. For demo purposes, the audio is gathered over a finite period,
reconstructed into a single variable, and then simply played back.
However, the same construction could be used for continuous processing of
>> framesamples=160; fs=16000; totalframes=100;
>> for ii=1:totalframes
>> %do realtime processing here
Trevor Agus (2023). Realtime audio input (https://www.mathworks.com/matlabcentral/fileexchange/32304-realtime-audio-input), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired by: Real Time Microphone and Camera data acquisition and audio-video processing
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.