Main Content

audiostreamer

Create and manage audio streams for playing and recording

Since R2025a

    Description

    The audiostreamer object provides a flexible I/O Interface for playing and recording audio in MATLAB®.

    • Work with streaming audio by specifying signals to be played in real time and processing audio as it is being recorded. You can specify callback functions to control the playing and processing of streaming audio.

    • Use audiostreamer to implement blocking workflows, where MATLAB does not process commands until playing and recording is finishing, or non-blocking workflows, where you can perform other processing while playing and recording audio.

    • Simultaneously play and record audio using full-duplex devices.

    • Use audiostreamer with multiple-channel signals and specify custom channel mappings.

    Creation

    Description

    streamer = audiostreamer creates a default audiostreamer object.

    example

    streamer = audiostreamer(mode) returns an audiostreamer object with the specified mode.

    streamer = audiostreamer(mode,fs) creates an audiostreamer object with the SampleRate property set to fs.

    streamer = audiostreamer(___,Name=Value) specifies options using one or more name-value arguments.

    Properties

    expand all

    I/O Interface

    Operating mode, specified as "player", "recorder", or "full-duplex".

    Data Types: char | string

    Audio driver, specified as "DirectSound", "ASIO", or "WASAPI". Windows is the only OS with multiple options, and the default is "DirectSound".

    Data Types: char | string

    Name of the audio output device, specified as one of the strings returned by getPlayerNames.

    Data Types: char | string

    Name of the audio input device, specified as one of the strings returned by getRecorderNames.

    Data Types: char | string

    Sample rate of the device in Hertz, specified as a positive scalar. The default value is the default rate of the Player or Recorder selected at object construction.

    Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Advanced

    Samples per device buffer, specified as a positive integer or "auto". Use "auto" to use the optimal frame size for the device, which can change every frame and it could be different for the player and the recorder. For ASIO, it is generally fixed by the device (see asiosettings).

    Data Types: char | string | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Mapping between columns of input matrix and channels of the audio player, specified as a scalar or as a vector of valid channel indices. The default value of this property is [], which means that the default one-to-one channel mapping is used.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Mapping between channels of the audio recorder and columns of the output matrix, specified as a scalar or as a vector of valid channel indices. The default value of this property is [1], which means that only channel 1 is recorded.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Bit format used by the device, specified as "int24", "int16", "single".

    Data Types: char | string

    Set WASAPI exclusive mode, specified as "on" or "off". If this property is "off", the device remains available to other applications on the same computer.

    This property applies only when Driver is "WASAPI".

    Data Types: char | string

    Behavior when a frame is dropped in full-duplex mode, specified as "off", "dropPlayer", or "dropRecorder".

    When ConstantLatency is "off", latency is not constant after a dropout because a frame of silence is inserted in the output, and no output or input frames are dropped to compensate. Therefore, dropouts cause an increase in latency by default.

    When ConstantLatency is "dropPlayer", the audiostreamer drops late output frames from the output queue when they become available, therefore preserving the same latency. This option works best for sweeptone measurements, because the impzest result is invalidated only for the frequencies that were dropped.

    When ConstantLatency is "dropRecorder", the audiostreamer drops the same number of input samples as the number of samples of silence inserted into the output. This option works with adaptive filters, but it does not work with impzest because the playback signal no longer matches the stimulus (zeros have been inserted).

    Data Types: char | string

    Callbacks

    Callback function for when recorded audio is available to read, specified as a function handle. The audiostreamer calls the RecorderFcn function asynchronously when the number of recorded samples reaches RecorderMinSamples. The first argument passed to the callback function is the audiostreamer object, and the second argument is an event structure. The event structure contains the type of event ("Recorder") in the Type field and the current number of available recorded samples in the NumRecorderSamples field.

    Minimum number of samples before the audiostreamer calls the RecorderFcn callback, specified as a positive integer.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Callback function to provide audio for the output queue, specified as a function handle. The audiostreamer calls the PlayerFcn function asynchronously when the number of samples in the output queue reaches PlayerMinSamples. The first argument passed to the callback function is the audiostreamer object, and the second argument is an event structure. The event structure contains the type of event ("Player") in the Type field and the number of samples in the output queue in the NumPlayerSamples field.

    Minimum number of samples required in the output queue when playing, specified as a positive integer. When the output queue drops to this number of samples, the audiostreamer calls the PlayerFcn.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Callback function for when the recorder has completed recording the number of requested samples (when calling record or playrec with a specified number of samples), specified as a function handle which the audiostreamer calls asynchronously. The first argument passed to the callback function is the audiostreamer object, and the second argument is an event structure. The event structure contains the type of event ("RecorderCompleted") in the Type field and the current stream time, according to getStreamTime, in the StreamTime field.

    Callback function for when the output queue is empty and the device is outputting silence, specified as a function handle which the audiostreamer calls asynchronously. The audiostreamer also calls this function when a dropout occurs. The first argument passed to the callback function is the audiostreamer object, and the second argument is an event structure. The event structure contains the type of event ("PlayerCompleted") in the Type field and the current stream time, according to getStreamTime, in the StreamTime field.

    Callback function for when playback experiences an underrun, which is silence between played audio, specified as a function handle which the audiostreamer calls asynchronously after the audio has resumed playing. The first argument passed to the callback function is the audiostreamer object, and the second argument is an event structure. The event structure contains the type of event ("PlayerUnderrun") in the Type field and the number of dropped samples in the SamplesUnderrun field.

    Resources

    This property is read-only.

    Maximum number of player channels available on the device, returned as a positive integer.

    Data Types: int32

    This property is read-only.

    Maximum number of recorder channels available on the device, returned as a positive integer.

    Data Types: int32

    Buffers

    This property is read-only.

    Number of samples in the player output queue, returned as a positive integer.

    Data Types: double

    This property is read-only.

    Number of samples available to read, returned as a positive integer.

    Data Types: double

    Object Functions

    playPlay audio on device
    recordRecord from audio device
    readGet recorded audio data
    playrecPlay and record simultaneously
    waitforWait for playback and/or recording to end
    pausePause playing and/or recording
    resumeResume paused playing and/or recording
    stopStop playing and/or recording
    setupConfigure audio device for operation
    releaseRelease audio device
    measureLoopbackLatencyMeasure device loopback latency
    getStreamTimeGet stream time in seconds
    getUnderrunCountGet number of underrun samples
    isPlayingIndicate if audio device is currently playing
    isRecordingIndicate if audio device is currently recording
    isPlayerPausedIndicates if playback is currently paused
    isRecorderPausedIndicates if recording is currently paused
    getAudioDevicesAvailable audio devices
    getPlayerNamesPlayer device names
    getRecorderNamesRecorder device names
    getDriversAvailable drivers on current OS

    Examples

    collapse all

    Read in an audio signal from a file. Create an audiostreamer object for playing audio with the same sample rate as the signal.

    [x,fs] = audioread("Counting-16-44p1-mono-15secs.wav");
    as = audiostreamer("player",fs);

    Call play with the audiostreamer and the data to play the audio. By default, this function blocks MATLAB execution until the audio is finished playing.

    play(as,x)

    You can also call play with the "non-blocking" argument to play the audio without blocking MATLAB execution.

    play(as,x,"non-blocking")

    You can record and play audio frame by frame to process streaming audio with the audiostreamer. Create an audiostreamer in "full-duplex" mode to both play and record audio with the same object. Specify a frame size N to process the audio 15 times per second.

    as = audiostreamer("full-duplex");
    N = round(as.SampleRate/15);

    Create an audioLevelMeter to measure the peak level of the streaming audio.

    lm = audioLevelMeter(SampleRate=as.SampleRate,WindowLength=N);
    visualize(lm);

    Figure Audio Meter contains an object of type uiaudiometer.

    Start recording audio with the audiostreamer. Then, in a 10-second-long stream loop, read in a frame of audio, measure the peak level with the audioLevelMeter, and play back the same frame of audio. You can use this pattern to process streaming audio and play back the processed audio.

    record(as)
    t = tic;
    while toc(t) < 10
        x = read(as,N); % blocks until N samples are available
        lm(x);
        play(as,x)
    end

    Figure Audio Meter contains an object of type uiaudiometer.

    stop(as)

    Create an audiostreamer object with the "recorder" mode.

    as = audiostreamer("recorder");

    Call record to start recording with the audiostreamer. The audiostreamer will record continuously until you pause or stop the recording. Use the MATLAB pause function to wait for three seconds, then call stop on the audiostreamer object to stop recording.

    record(as)
    pause(3)
    stop(as)

    Call read to get all of the available recorded audio from the audiostreamer.

    x = read(as);

    Alternatively, you can call record with a specified number of samples after which the recording will automatically stop. Calling read with the specified number of samples will block MATLAB execution until that number of samples has been recorded.

    N = 3*as.SampleRate; % 3 seconds of samples
    record(as,N)
    y = read(as,N);

    You can play and record audio simultaneously on a full-duplex device using audiostreamer. In this example, you use a full-duplex device to measure an impulse response. Create an audiostreamer object in "full-duplex" mode with a sample rate of 48,000 Hz and one output channel.

    as = audiostreamer("full-duplex",48e3, ...
        Driver="ASIO", ...
        Player="Focusrite USB ASIO", ...
        PlayerChannels=1, ...
        Recorder="Focusrite USB ASIO");

    Create a sweeptone excitation signal. The excitation signal has a two-second exponential swept sine followed by one second of silence. Call playrec to play the excitation signal while recording simultaneously. Calling playrec with the output argument blocks MATLAB until the recording is finished.

    x = sweeptone(2,1,as.SampleRate);
    y = playrec(as,x,size(x,1));

    Use impzest to compute the impulse response from the excitation and recorded response. Plot the impulse response.

    ir = impzest(x,y);
    t = (1:size(ir,1))/as.SampleRate;
    plot(t,ir)
    xlabel("Time (s)")

    Figure contains an axes object. The axes object with xlabel Time (s) contains an object of type line.

    You can use a callback function to asynchronously provide audio to the audiostreamer to play. Define your callback as a function that generates pink noise and plays it on the audiostreamer. The callback function takes in the audiostreamer object and a struct containing information about the event that triggered the callback. Create an audiostreamer object and set the PlayerFcn callback to the myPlayerFcn function handle.

    function myPlayerFcn(obj,ev)
        y = randn(1024,1);
        play(obj,y)
    end
    
    as = audiostreamer;
    as.PlayerFcn = @myPlayerFcn;

    Now calling play on the audiostreamer will call the PlayerFcn callback whenever the number of samples in the output queue drops below PlayerMinSamples.

    play(as)
    pause(3)
    stop(as)

    You can use a callback function to asynchronously read recorded audio from the audiostreamer. Define the RecorderFcn callback as an anonymous function that takes the audiostreamer object and passes the available recorded audio to a spectrumAnalyzer object.

    as = audiostreamer("recorder");
    analyzer = spectrumAnalyzer(SampleRate=as.SampleRate, ...
        PlotAsTwoSidedSpectrum=false,FrequencyScale="log");
    
    as.RecorderFcn = @(obj,~)analyzer(read(obj));

    Now calling record on the audiostreamer calls the RecorderFcn when the number of recorded samples reaches RecorderMinSamples.

    record(as)
    pause(10)
    stop(as)

    Version History

    Introduced in R2025a