Matlab Write Audio Plugin
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Software development
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to developing audio plugins using MATLAB's Audio Toolbox. It covers the lifecycle of audioPlugin and audioPluginSource classes, ensuring code is compatible with MATLAB's codegen requirements for VST and AU deployment. The documentation details best practices for state management, buffer handling, filter design, and the use of codegen-compatible DSP objects to ensure plugins pass validation and perform reliably in DAW environments.
What it does
- Guides the creation of classdef files inheriting from audioPlugin or audioPluginSource.
- Provides patterns for managing plugin state, sample rate changes, and audio frame processing.
- Offers strategies for codegen-compatible buffer management and fixed-size processing.
- Explains how to use built-in DSP System Toolbox objects for efficient audio processing.
- Details the validation process using validateAudioPlugin to ensure deployment readiness.
- Outlines commands for generating VST, AU, and standalone binaries from MATLAB code.
When to use it
- When developing custom audio effects or generators in MATLAB.
- When preparing a MATLAB audio algorithm for deployment as a VST or AU plugin.
- When troubleshooting failures in validateAudioPlugin or generateAudioPlugin.
- When integrating deep learning inference into real-time audio processing chains.
Advantages
- Ensures compatibility with real-time DAW requirements through strict codegen patterns.
- Reduces development time by leveraging optimized, built-in DSP System Toolbox objects.
- Provides a clear path from algorithm prototyping to deployable binary formats.
- Includes specific patterns for complex audio tasks like spectral processing and variable-to-fixed frame conversion.
Usage examples
- “How do I structure a basic audio effect plugin in MATLAB?”
- The agent provides a classdef template inheriting from audioPlugin, including the required process and reset methods, property definitions, and the PluginInterface block.
- “My plugin fails validateAudioPlugin due to variable-size arrays. How do I fix this?”
- The agent explains how to pre-allocate state to the maximum required size and use explicit indexing to ensure fixed-size properties, preventing codegen errors.
- “How can I convert my MATLAB audio plugin into a VST3 file?”
- The agent provides the generateAudioPlugin command with the -vst3 flag and explains the platform-specific requirements for binary generation.
- “How do I handle variable frame sizes from a DAW in my plugin?”
- The agent demonstrates the use of dsp.AsyncBuffer to buffer incoming audio and process it in fixed-size frames required by algorithms like FFT or neural networks.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-write-audio-plugin/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-write-audio-plugin.zip -d .agents/skills
Documentation by MathWorks
Writing Audio Plugins in MATLAB
When To Use
Creating audio effect or generator plugins (classdef inheriting from
audioPluginoraudioPluginSource)Troubleshooting
validateAudioPluginorgenerateAudioPluginfailuresConverting a MATLAB audio algorithm into a deployable VST/AU plugin
Integrating deep learning inference into a real-time audio plugin
When NOT To Use
General MATLAB class authoring unrelated to audio plugins
Audio file I/O, feature extraction, or analysis (no plugin involved)
Simulink audio processing blocks
Writing Audio Toolbox functions that are not plugins (e.g.,
audioDatastore,audioFeatureExtractor)
Structure
Every audio plugin is a classdef with %#codegen, public tunable properties, a Constant PluginInterface, and methods process + reset.
classdef MyPlugin < audioPlugin
%#codegen
properties
Gain = 0.5
Cutoff = 1000
end
properties (Access = private)
pSR = 44100
pB = [1 0 0]
pA = [1 0 0]
pState = zeros(2, 2) % (filterOrder, numChannels)
end
properties (Constant)
PluginInterface = audioPluginInterface( ...
audioPluginParameter('Gain', ...
DisplayName='Gain', Label='dB', Mapping={'lin', 0, 1}), ...
audioPluginParameter('Cutoff', ...
DisplayName='Cutoff', Label='Hz', Mapping={'log', 20, 20000}), ...
InputChannels=2, OutputChannels=2)
end
methods
function y = process(plugin, x)
[y, plugin.pState] = filter(plugin.pB, plugin.pA, x, plugin.pState);
y = y * plugin.Gain;
end
function reset(plugin)
plugin.pSR = getSampleRate(plugin);
plugin.pState = zeros(2, 2);
designFilter(plugin);
end
function set.Cutoff(plugin, val)
plugin.Cutoff = val;
designFilter(plugin); %#ok<MCSUP>
end
end
methods (Access = private)
function designFilter(plugin)
wn = plugin.Cutoff / (plugin.pSR / 2);
wn = max(eps, min(wn, 1 - eps));
[plugin.pB, plugin.pA] = butter(2, wn);
end
end
endSource plugins inherit audioPluginSource, omit InputChannels, and process takes no audio input — use getSamplesPerFrame(plugin) for output frame size.
System Object hybrids (matlab.System & audioPlugin) require (StrictDefaults), isInputSizeMutableImpl returning true, and stepImpl/resetImpl instead of process/reset. Use only when user requests Simulink compatibility.
Plugin Lifecycle
Constructor — Construct all sub-objects with literal arguments.
getSampleRatereturns 44100 here; use for initial buffer sizing only.reset— Called when sample rate or frame size changes. CachegetSampleRate(plugin)inpSR. Recompute all SR-dependent values. Callreset()on every sub-object (after setting their sample rate).process— Called per audio frame. Returndoubleoutput sized[N, numOutputChannels]. Never assign to properties registered inaudioPluginParameter— for output meters, keep properties public but unregistered.Set methods — Recompute derived values (coefficients, buffer sizes) when parameters change. Add
%#ok<MCSUP>only when the set method actually accesses another property throughobj.PropertyNameor calls a method that does (e.g.,designFilter(plugin)fromset.Cutoff). Do not add it preemptively — only suppress warnings that checkcode actually raises on that line.Save/load (optional, MATLAB-only) — Only needed when the plugin has private state that
resetcannot reconstruct from parameters and sample rate (e.g., loaded data, handle sub-objects with internal buffers). Not compiled into generated VSTs/standalones — DAW hosts persist parameters via the plugin interface and callreseton restore. Seereferences/advanced-patterns.mdfor the pattern.
Codegen Requirements
All code must be codegen-compatible. validateAudioPlugin sweeps 5 sample rates (8000–192000), frame sizes 2.^(1:13)+1 (max 8193), and all parameter extremes.
Always use built-in functions over hand-implementations. Prefer toolbox functions in this order: Audio Toolbox → DSP System Toolbox → Signal Processing Toolbox → base MATLAB. If unsure whether a codegen-compatible built-in exists for an operation, consult references/available-functions.md before implementing manually.
Buffers and State
Pre-allocate all state to maximum needed size. Codegen locks property size from the constructor's last assignment — allocate at the maximum the parameter can reach, then index into the active region at runtime.
Shift with indexed assignment:
buf(1:end-N) = buf(N+1:end); % shift left by N
buf(end-N+1:end) = newData; % fill tailNever concatenate to shift — [buf(N+1:end); zeros(N,ch)] produces a variable-size result that codegen rejects on assignment to a fixed-size property.
Never use : on the column dimension when assigning to a fixed-size property — codegen treats x(i,:) as variable-size. Index columns explicitly: [x(i,1), x(i,2)].
Initialize arrays that will hold complex values with complex(zeros(...)) — not bare zeros(...). Codegen locks the real/complex attribute from the first assignment. If the array starts real, assigning FFT output into it later fails with "left-hand side constrained to be non-complex."
dsp.AsyncBuffer capacity must exceed the largest single write the plugin will receive. validateAudioPlugin delivers frames up to 8193 samples; account for that plus any overlap when sizing the buffer.
When filter() input comes from a sub-object (e.g., crossoverFilter), codegen cannot propagate the column count — the returned state becomes variable-size. Process channels explicitly:
[low(:,1), plugin.pState(:,1)] = filter(b, a, low(:,1), plugin.pState(:,1));
[low(:,2), plugin.pState(:,2)] = filter(b, a, low(:,2), plugin.pState(:,2));Enum Parameters (Different-Length Values)
Use Style='dropdown' for 3+ values, 'vrocker'/'vtoggle' for exactly 2.
When enum values have different character lengths ('On'/'Off', 'Short'/'VeryLong'), prefer a separate int32 enum class file. The framework can handle char padding internally, but an explicit enum class produces cleaner generated code with typed dispatch instead of string comparisons:
% MyMode.m
classdef MyMode < int32
enumeration
Normal (0)
Aggressive (1)
Subtle (2)
end
endPlugin property: Mode = MyMode.Normal with Mapping={'enum','Normal','Aggressive','Subtle'}.
Derived Values from Parameters
When computing normalized frequency or delay indices from parameters, clamp the result:
wn = plugin.Cutoff / (plugin.pSR / 2);
wn = max(eps, min(wn, 1 - eps)); % keep in valid (0,1) range for butter/chebyClamp delay-line read indices to [1, bufferLength]. This prevents out-of-bounds at extreme sample rates or parameter settings that validateAudioPlugin will exercise.
Switch Completeness
Every switch that assigns a variable must include otherwise with a safe default — codegen requires all branches to define the same outputs.
Sub-Objects
Construct with literal arguments in the constructor. In reset, propagate sample rate then reset:
function reset(plugin)
fs = getSampleRate(plugin);
setSampleRate(plugin.pEcho, fs);
reset(plugin.pEcho);
plugin.pCompressor.SampleRate = fs;
reset(plugin.pCompressor);
endCall sub-plugins as process(plugin.pSub, x). Call System Objects as plugin.pObj(x). Forward parameter changes in set methods.
External Data and Runtime-Only Calls
Load data files:
coder.load('data.mat')in the constructor — baked into the binaryGuard non-codegen calls: wrap
fprintf/disp/plotinif isempty(coder.target)
Validation
validateAudioPlugin -nomex ClassName % structural + testbench
validateAudioPlugin ClassName % full MEX codegen
generateAudioPlugin ClassName % produce VST/AU binaryAfter validation passes:
Run
checkcodeon all produced.mfiles — resolve every warning by renaming or restructuring, not by adding%#oksuppressions (except%#ok<MCSUP>in set methods). Re-run checkcode to confirm zero warnings remain.Verify functional behavior: instantiate,
setSampleRate,reset, process a test signal, confirm output matches intent.
Generation
Default output is VST 2. Use flags to select other formats:
| Flag | Format | Platform |
|---|---|---|
-vst | VST 2 (default) | Windows, macOS |
-vst3 | VST 3 | Windows, macOS |
-au | Audio Unit v2 | macOS only |
-auv3 | Audio Unit v3 | macOS only |
-exe | Standalone executable | Windows, macOS |
-juceproject | JUCE project (source code) | All (including Linux) |
When the user requests an output format unavailable on the current platform (e.g., AU on Windows, or any compiled binary on Linux), explain the constraint and suggest the closest alternative (-juceproject on Linux, -vst/-vst3 on Windows instead of AU).
References
references/available-functions.md— Built-in streaming DSP objects (prefer over manual implementations)references/advanced-patterns.md— AsyncBuffer, modulated delay, save/load, codegen edge casesreferences/parameters.md— Mapping laws, multi-bus I/O, grid layout constraintsreferences/grid-layout.md— Grid layout syntax, row allocation withDisplayNameLocationreferences/deep-learning.md— Neural network inference withcoder.loadDeepLearningNetwork
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md10.1 KiB
- manifest.yaml524 B
- references/advanced-patterns.md6.8 KiB
- references/available-functions.md9.0 KiB
- references/deep-learning.md8.0 KiB
- references/grid-layout.md3.9 KiB
- references/parameters.md1.4 KiB
references/available-functions.md
Available Functions for Audio Plugins
Use these codegen-compatible objects/functions instead of reimplementing DSP from scratch. Construct objects in the constructor, configure in reset, call in process via y = obj(x).
Delays and Buffers
| Object | Purpose |
|---|---|
dsp.VariableFractionalDelay | Fractional delay with interpolation — set MaximumDelay at construction |
dsp.VariableIntegerDelay | Integer delay line (no interpolation) |
dsp.AsyncBuffer | Asynchronous FIFO for variable-to-fixed frame conversion |
dsp.Delay | Fixed integer delay |
Filters
Key streaming filters (construct once, call per frame):
| Object | Purpose |
|---|---|
dsp.SOSFilter | SOS IIR filter — tunable Nx3 Numerator/Denominator matrices |
dsp.FIRFilter | FIR direct-form |
dsp.NotchPeakFilter | Tunable notch/peak (frequency, bandwidth) |
dsp.VariableBandwidthFIRFilter | FIR with tunable CenterFrequency, Bandwidth, FilterType, SampleRate |
dsp.VariableBandwidthIIRFilter | IIR with tunable CenterFrequency, Bandwidth, FilterType, SampleRate |
dsp.DCBlocker | DC offset removal |
dsp.AllpassFilter | Phase manipulation (WDFAllpass or Lattice) |
octaveFilter | Octave/fractional-octave band — tunable CenterFrequency, Bandwidth, SampleRate |
weightingFilter | A/C/K-weighting — tunable SampleRate |
multibandParametricEQ | Multi-band parametric EQ — tunable gains, frequencies, Q |
graphicEQ | Graphic EQ — tunable Gains vector, SampleRate |
crossoverFilter | Multi-band splitting — tunable CrossoverFrequencies, CrossoverSlopes, SampleRate |
shelvingFilter | Shelving EQ — tunable Gain, Slope, CutoffFrequency. SampleRate is non-tunable — construct with max expected rate, or use designShelvingEQ + filter() |
gammatoneFilterBank | Auditory filter bank — tunable SampleRate |
octaveFilterBank | Multi-band octave filter bank — tunable SampleRate |
dsp.FilterCascade | Cascade multiple filter objects into one |
dsp.LMSFilter / dsp.RLSFilter | Adaptive filters (noise cancellation, system ID) |
Also available: dsp.IIRFilter, dsp.AllpoleFilter, dsp.CoupledAllpassFilter, dsp.HighpassFilter, dsp.LowpassFilter, dsp.Differentiator
Filter design (compute coefficients in set methods or reset):
designParamEQ— NV syntax:designParamEQ(Gain=G, QualityFactor=Q, CenterFrequency=Fc, Orientation="row")where Fc is normalized (0–1). FilterOrder=2 returns 1×3 → usefilter(B, A, x, state). Higher orders → Nx3 → usedsp.SOSFilterdesignShelvingEQ— positional:designShelvingEQ(gain, slope, Fc, type, Orientation="row")→ 1×3designVarSlopeFilter— positional:designVarSlopeFilter(slope, Fc, type, Orientation="row")→ Nx3 → usedsp.SOSFilterdesignVarSlopeFilter,designParamEQ,designShelvingEQ— useOrientation="row"(default) R2024a+butter,cheby1,ellip— classic IIR design (use withfilter(b, a, x, state))
One-liner filter design + implementation (return filter objects, construct once): designLowpassFIR, designHighpassFIR, designBandpassFIR, designBandstopFIR, designHalfbandFIR, designLowpassIIR, designHighpassIIR, designBandpassIIR, designBandstopIIR, designHalfbandIIR, designNotchPeakIIR, designFracDelayFIR, designMultirateFIR
Low-level: filter, sosfilt (with state), xcorr, levinson, lpc
Codegen note for lpc: returns complex when the autocorrelation matrix is near-singular — always wrap with real(). Use a fixed order to keep the output size fixed: a = real(lpc(frame, 12)) returns 1×13.
Reverb and Spatial
| Object | Purpose |
|---|---|
reverberator | Plate/room reverb — tunable PreDelay, WetDryMix, Diffusion, DecayFactor, HighCutFrequency, SampleRate |
dsp.FrequencyDomainFIRFilter | Efficient long-FIR convolution (HRTF, room IRs) |
interpolateHRTF | Interpolate HRTFs for dynamic source position |
ambisonicEncoderMatrix / ambisonicDecoderMatrix | Ambisonics encoding/decoding matrices |
Oscillators and Generators
| Object | Purpose |
|---|---|
audioOscillator | Sine, square, sawtooth waveform generation |
dsp.NCO | Numerically controlled oscillator (FM/PM synthesis) |
dsp.ColoredNoise | White, pink, brown noise |
wavetableSynthesizer | Wavetable oscillator — tunable Frequency, Amplitude, SampleRate |
shiftPitch | Pitch shifting — function, call per frame |
stretchAudio | Time stretching — codegen requires Method='vocoder', LockPhase=false |
Also: dsp.SineWave (pure sine)
Dynamics
compressor, expander, limiter, noiseGate — all tunable, all have tunable SampleRate
Transforms
| Object | Purpose |
|---|---|
dsp.FFT / dsp.IFFT | Streaming FFT/IFFT — fixed frame size, wrap with dsp.AsyncBuffer |
dsp.STFT / dsp.ISTFT | Streaming STFT — fixed frame size, wrap with dsp.AsyncBuffer |
dsp.DCT | Discrete Cosine Transform |
dsp.AnalyticSignal | Hilbert transform — fixed frame size, wrap with dsp.AsyncBuffer |
goertzel | Single-bin DFT (tuner/pitch detection at known frequency) |
mdct / imdct | MDCT pair — call per frame with PadInput=false for streaming (mdct(frame, win, 'PadInput', false)), use with kbdwin. Output is winLen/2 coefficients; overlap-add imdct outputs for reconstruction. |
Also: dsp.ZoomFFT, dsp.SpectrumEstimator, dsp.PhaseExtractor, dsp.PhaseUnwrapper
Standard window functions are codegen-compatible: hann, hamming, blackman, kaiser, kbdwin, etc.
Interpolation and Rate Conversion
| Object | Purpose |
|---|---|
dsp.FIRDecimator / dsp.FIRInterpolator | Integer-ratio decimation/interpolation |
dsp.FarrowRateConverter | Arbitrary sample rate conversion |
dsp.SampleRateConverter | Combined multi-stage rate conversion |
Also: dsp.FIRRateConverter, dsp.FIRHalfbandDecimator, dsp.FIRHalfbandInterpolator, dsp.IIRHalfbandDecimator, dsp.IIRHalfbandInterpolator, dsp.Channelizer, dsp.ChannelSynthesizer, dsp.SubbandAnalysisFilter, dsp.SubbandSynthesisFilter, dsp.ComplexBandpassDecimator
Feature Extraction and Analysis
Streaming objects (set SampleRate in reset): loudnessMeter, splMeter, voiceActivityDetector, detectspeechnn, acousticRoughness, octaveSpectrumEstimator
Per-frame functions (pass sample rate as argument): pitch, spectralCentroid, spectralCrest, spectralEntropy, spectralFlatness, spectralFlux, spectralKurtosis, spectralRolloffPoint, spectralSkewness, spectralSlope, spectralSpread, harmonicRatio, mfcc, gtcc, melSpectrogram, cepstralCoefficients, audioDelta, zerocrossrate
Deep Learning Inference
coder.loadDeepLearningNetwork, predict, dlarray/extractdata, audioPluginConfig — see references/deep-learning.md for the full pattern.
Shipping Pretrained Networks
audioPretrainedNetwork(name) returns a dlnetwork ready for coder.loadDeepLearningNetwork. Available: "yamnet" (521-class sound classification), "vggish" (audio embeddings), "openl3" (embeddings), "crepe" (pitch), "vadnet" (voice activity). Save to .mat for codegen: net = audioPretrainedNetwork("yamnet"); save('yamnet.mat','net').
Codegen-compatible preprocessing functions (handle resampling internally):
yamnetPreprocess(audio, fs)— resamples to 16 kHz, computes [96x64x1xK] log-mel patchesvggishPreprocess(audio, fs)— same pipeline, different log offset
These are marked #codegen and can be called directly inside process or inference helper functions.
Utility
| Object | Purpose |
|---|---|
dsp.ParameterSmoother | Exponential smoothing for click-free parameter transitions. Call once per frame with the scalar target value — returns one smoothed scalar. Passing a vector silently uses only the first element. Use 'Smoothing factor' mode in plugins (SampleTime is non-tunable and SR-dependent). |
dsp.MovingRMS | Running RMS level |
dsp.MedianFilter | Running median filter |
dsp.Counter | Sample/frame counter |
audioTimeScaler | Phase-vocoder time stretching — tunable SpeedFactor, SampleRate |
Also: dsp.MovingAverage, dsp.MovingStandardDeviation, dsp.MovingMaximum, dsp.MovingMinimum, dsp.PeakToRMS, dsp.ZeroCrossingDetector, dsp.HampelFilter
Usage Notes
Do NOT call
release()in generated code — the object may be unusable afterwardDo NOT use
dsp.BiquadFilter(deprecated) — usedsp.SOSFilterinsteadcoder.extrinsicevaluates at compile time only — the result becomes a constantObjects with tunable
SampleRate(set directly inreset):reverberator,audioOscillator,wavetableSynthesizer,compressor,expander,limiter,noiseGate,octaveFilter,weightingFilter,multibandParametricEQ,graphicEQ,gammatoneFilterBank,octaveFilterBank,splMeter,audioTimeScaler,loudnessMeter,acousticRoughness,octaveSpectrumEstimator
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/signal-processing/matlab-write-audio-plugin · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-write-audio-plugin.zip