Sources and synthesis
What the added sound sources take and return. audiosampler also has a
guide, and audiovorbis has its own page; the reasons behind
each module are in Additions beyond CircuitPython.
audiocore
Generated from audiocore.pyi; the file reads on its own.
Audio sample sources: raw PCM in memory, WAV files, and the calls that read a source’s buffers directly.
RawSample plays a buffer you already hold and WaveFile streams a wav
file. Both are audio samples, the objects every other audiodsp module reads
from __future__ import annotations
from and writes to: each has sample_rate, bits_per_sample and
channel_count, and hands its audio to whatever plays it. The module has
CircuitPython’s own audiocore API, so one script runs on both.
get_buffer, reset_buffer and get_structure pull audio out of any audio
sample by hand, with no output device, which is how a test reads what a chain
of nodes produces.
- class audiocore.RawSample(buffer, *, channel_count=1, sample_rate=8000, single_buffer=True)[source]
Bases:
objectPlays a buffer of raw PCM samples that you provide.
The buffer is read in place and never copied, so keep it unchanged while the sample plays. Samples are 8 or 16 bits, signed or unsigned, taken from the buffer’s type.
- Parameters:
buffer – A
bytearrayor anarray.arrayof type'b','B','h'or'H'. A'b'or'h'array holds signed samples; the others hold unsigned samples.channel_count – 1 for mono, 2 for interleaved stereo.
sample_rate – Frames per second.
single_buffer – True to play the buffer once through as one block. False splits it into two halves handed out alternately, so the buffer’s length must be a multiple of twice the size of one frame.
- Raises:
ValueError – The buffer is not one of the types above, or
single_bufferis False and its length is not a multiple ofchannel_counttimes the sample size times two.
- sample_rate
Frames per second. You can change it while the sample plays, to 1 or more, to play it faster or slower.
- property bits_per_sample
Size of one sample in bits: 8 or 16.
- property channel_count
Number of channels: 1 or 2.
- deinit()[source]
Release the sample. Every later use raises
ValueError.
- class audiocore.WaveFile(file, buffer=None, /)[source]
Bases:
objectStreams audio from a
.wavfile.The file stays open and is read a block at a time while the sample plays. Uncompressed PCM of 16 bits or fewer, mono or stereo, is supported: 8-bit samples are unsigned and 16-bit samples are signed.
- Parameters:
file – A path, or a binary file object opened for reading.
buffer – A writable buffer, 8 to 1024 bytes and a multiple of 8, to read blocks into. Leave it out to let the sample allocate its own.
- Raises:
ValueError – The file is not a supported WAV file, or the buffer is the wrong size.
OSError – The file cannot be opened or read.
- sample_rate
Frames per second. You can change it while the sample plays, to 1 or more, to play it faster or slower.
- property bits_per_sample
Size of one sample in bits: 8 or 16.
- property channel_count
Number of channels: 1 or 2.
- deinit()[source]
Release the sample and close its file. Every later use raises
ValueError.
- audiocore.get_buffer(sample, /)[source]
Read the next block of audio from a sample.
- Parameters:
sample – Any audio sample: a
RawSample, aWaveFile, or a node from another audiodsp module.- Returns:
(status, block).statusis 0 when this was the last block, 1 when more follow and 2 on an error;blockis a copy of the audio as a bytememoryview, and None when the status is 2. Its length is in bytes, whatever the sample width.- Raises:
TypeError –
sampleis not an audio sample.ValueError – The sample was deinitialised.
- audiocore.reset_buffer(sample, /)[source]
Rewind a sample so the next
get_bufferstarts from its beginning.- Raises:
TypeError –
sampleis not an audio sample.ValueError – The sample was deinitialised.
- audiocore.get_structure(sample, /)[source]
Describe how a sample hands out its audio.
- Returns:
(single_buffer, samples_signed, max_buffer_length, spacing)– whether one block holds the whole sample, whether samples are signed, the most bytes one block can hold, and the bytes between one channel’s samples.- Raises:
TypeError –
sampleis not an audio sample.ValueError – The sample was deinitialised.
audiomp3
Generated from audiomp3.pyi; the file reads on its own.
Play MP3 files.
MP3Decoder reads an MP3 file while it plays and hands out signed 16-bit
audio. It is an audio sample, so it plays wherever an audiocore.WaveFile
does. The module has CircuitPython’s own audiomp3 API, so one script runs on
both.
The decoder reads its file during playback, so keep the file open while the sample plays.
- class audiomp3.MP3Decoder(file, buffer=None, /)[source]
Bases:
objectDecodes an MP3 file as it plays.
- Parameters:
file – A path, or a file object opened for reading in binary mode.
buffer – A writable buffer to use for the decoder’s input and output instead of allocating one. Leave it out to let the decoder allocate its own.
- Raises:
TypeError –
fileis a file opened in text mode.OSError – The file cannot be opened or read.
RuntimeError – The file has no MP3 frames the decoder can read.
MemoryError – The decoder’s buffers do not fit.
- file
The file being decoded. Assign a new file object, opened in binary mode, to play another MP3 with the same decoder.
- sample_rate
Frames per second, from the file. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2, from the file.
- property rms_level
How loud the most recently decoded block was, in 16-bit sample units: the square root of the sum of its squared samples, divided by the number of samples. Louder audio reads higher; it is not a true RMS, so compare readings with each other rather than with a decibel scale.
- property samples_decoded
How many frames have been decoded so far.
- open(path, /)[source]
Open an MP3 file by path and decode that instead.
- Parameters:
path – The file to open. It is opened for reading in binary mode.
- Raises:
OSError – The file cannot be opened or read.
- deinit()[source]
Release the decoder and close nothing else. Every later use raises
ValueError.
synthio
Generated from synthio.pyi; the file reads on its own.
Multi-channel audio synthesis.
This is CircuitPython’s own synthio API, so one script plays on both. A
Synthesizer plays Note objects, or plain MIDI note numbers, through an
Envelope and a waveform. A Note can take a Biquad filter, a ring
modulator, and a BlockInput on its amplitude, pitch bend and panning: a
number, an LFO or a Math block that is advanced while the synthesizer
plays. A MidiTrack plays a stream of MIDI note events.
Beyond CircuitPython’s own API this build adds lfo_tick,
Synthesizer.max_polyphony, Synthesizer.refused and
Synthesizer.release_then_press.
- synthio.waveform_max_length
16384. Pass it as a loop end to loop to the end of a waveform whatever its length.
- Type:
The most samples a waveform can have
- class synthio.EnvelopeState[source]
Bases:
objectWhich phase of its envelope a note is in.
- ATTACK
The note is in its attack phase.
- DECAY
The note is in its decay phase.
- SUSTAIN
The note is in its sustain phase.
- RELEASE
The note is in its release phase.
- class synthio.Envelope(*, attack_time=0.1, decay_time=0.05, release_time=0.2, attack_level=1.0, sustain_level=0.8)[source]
Bases:
tuple[float,float,float,float,float]An ADSR envelope with linear ramps.
A note starts at zero volume, rises to
attack_leveloverattack_timeseconds, falls tosustain_leveloverdecay_timeseconds, and when it is released falls to zero overrelease_time.If
sustain_levelis 0, the decay and sustain phases are omitted and the note counts as released as soon as the attack ends, as a plucked or struck instrument behaves.decay_timeis then ignored.If a note is released before its sustain phase, it falls with the slope of
sustain_level / release_time(orattack_level / release_timefor a plucked envelope).An envelope is an immutable tuple of its five values, in the order of the arguments.
- Parameters:
attack_time – Seconds to ramp from 0 to
attack_level. The default is 0.1. It cannot be negative.decay_time – Seconds to ramp from
attack_leveltosustain_level. The default is 0.05. It cannot be negative.release_time – Seconds to ramp from the current level to 0 on release. The default is 0.2. It cannot be negative.
attack_level – The peak level of the attack, from 0.0 to 1.0. The default is 1.0.
sustain_level – The level of the sustain phase relative to the attack level, from 0.0 to 1.0. The default is 0.8.
- Raises:
ValueError – A time is negative, or a level is outside 0.0 to 1.0.
- property attack_time
Seconds to ramp from 0 volume to the attack level.
- property decay_time
Seconds to ramp from the attack level to the sustain level.
- property release_time
Seconds to ramp down on release.
- property attack_level
The peak level of the attack phase, from 0.0 to 1.0.
- property sustain_level
The level of the sustain phase relative to the attack level, from 0.0 to 1.0.
- class synthio.FilterMode[source]
Bases:
objectThe type of a
Biquadfilter.- LOW_PASS
A low-pass filter.
- HIGH_PASS
A high-pass filter.
- BAND_PASS
A band-pass filter.
- NOTCH
A notch filter.
- LOW_SHELF
A low shelf filter.
- HIGH_SHELF
A high shelf filter.
- PEAKING_EQ
A peaking equalizer filter.
- class synthio.Biquad(mode, frequency, Q=Ellipsis, A=None)[source]
Bases:
objectA biquad filter, evaluated as a direct form 1 filter.
frequencyis the centre or corner frequency in Hz, depending on the mode.Qis the sharpness.Asets the gain of peaking and shelving filters asA = 10 ** (dB_gain / 40)and is ignored by the others.Because
frequency,QandAare block inputs, they can vary while the note plays. The filter’s internal state is not updated when the coefficients change; in practice, varying them slowly behaves as you would expect.- Parameters:
mode – The filter type.
frequency – The centre or corner frequency in Hz.
Q – The sharpness. The default is 0.7071067811865475.
A – The gain of peaking and shelving filters. The default is None.
- property mode
The type of filter. It cannot be changed.
- frequency
The centre or corner frequency of the filter in Hz.
- Q
The sharpness of the filter.
- A
The gain of a peaking or shelving filter,
10 ** (dB_gain / 40).
- class synthio.LFO(waveform=None, *, rate=1, scale=1, offset=0, phase_offset=0, once=False, interpolate=True)[source]
Bases:
objectA low-frequency oscillator block.
Every
rateseconds the LFO cycles through itswaveform. The output at any moment iswaveform[index] * scale + offset. The waveform’s'h'values are scaled so that -32768..32767 maps to -1.0..0.99996. With no waveform, a triangle is used.An LFO only updates while it is tied to a playing
Synthesizer, directly, through aNote, or through another block, and then it updates every 256 samples. Using one LFO as the input of several blocks is fine; tying it to several synthesizers is undefined. Thevalueis worked out when the LFO is made and whenever its synthesizer updates it, so changingoffsetalone does not changevalue.oncechanges how the waveform is interpolated. Withwaveform=array('h', [0, 100])andrate=1,once=Trueramps from 0 to 100 over one second and stays there, whileonce=Falseis a triangle with a one second period that peaks at half a second. Changingonceother than at a phase of 0 steps the output.- Parameters:
waveform – A buffer of signed 16-bit samples, or None for a triangle. Its values may be changed while it is in use.
rate – Cycles per second.
scale – A multiplier on the output.
offset – An addend on the output.
phase_offset – An addend on the phase, in cycles.
once – True to stop at the last output value, False to start again.
interpolate – True to interpolate linearly between values.
- property waveform
The waveform. It cannot be replaced, but its values may change.
- rate
The rate in Hz at which the LFO cycles through its waveform.
- offset
An addend on the LFO’s output.
- phase_offset
An addend on the LFO’s phase.
- scale
A multiplier on the LFO’s output.
- once
True if the waveform stops at its last output value, False if it starts again. This applies to the phase before
phase_offsetis added.
- interpolate
True if the waveform is interpolated linearly between values.
- property phase
The phase of the oscillator, from 0 to 1.
- property value
The value of the oscillator.
- class synthio.MathOperation[source]
Bases:
objectThe operation of a
Mathblock.Calling an operation, as in
MathOperation.SUM(a, b), makes aMathblock that performs it.- SUM
a + b + c. For a two input sum, set one argument to 0.0. To hold a control value for several subscribers, set two arguments to 0.0.
- ADD_SUB
a + b - c. For a two input subtraction, setbto 0.0.
- PRODUCT
a * b * c. For a two input product, set one argument to 1.0.
- MUL_DIV
a * b / c. Ifcis zero, the output is 1.0.
- SCALE_OFFSET
(a * b) + c.
- OFFSET_SCALE
(a + b) * c. For a two input multiplication, setbto 0.
- LERP
a * (1 - c) + b * c.
- CONSTRAINED_LERP
a * (1 - c') + b * c', wherec'is limited to 0.0 to 1.0.
- DIV_ADD
a / b + c. Ifbis zero, the output isc.
- ADD_DIV
(a + b) / c. For a two input quotient, setbto 0.0.
- MID
The middle of the three inputs.
- MAX
The biggest of the three inputs.
- MIN
The smallest of the three inputs.
- ABS
The absolute value of
a.
- class synthio.Math(operation, a, b=0, c=1)[source]
Bases:
objectAn arithmetic block that works on up to three inputs.
Like an
LFO, it only updates while it is tied to a playingSynthesizer, directly or through another block, and then every 256 samples. Its properties can change while it plays.- Parameters:
operation – What to compute.
a – The first input.
b – The second input.
c – The third input.
- a
The first input.
- b
The second input.
- c
The third input.
- operation
The function to compute.
- property value
The result of the last update.
- class synthio.Note(frequency, *, panning=0, amplitude=1, bend=0, waveform=None, waveform_loop_start=0, waveform_loop_end=Ellipsis, envelope=None, filter=None, ring_frequency=0, ring_bend=0, ring_waveform=None, ring_waveform_loop_start=0, ring_waveform_loop_end=Ellipsis)[source]
Bases:
objectOne note: a frequency, with optional waveform, envelope, filter, ring modulation, tremolo and bend.
If
waveformorenvelopeis None, the synthesizer’s default is used. Playing oneNoteon several synthesizers is undefined.- Parameters:
frequency – The base frequency in Hz.
panning – Where the note sits between the channels: -1 is left only, 0 is both and 1 is right only. A fractional value plays the nearer channel at full amplitude and the other at part of it.
amplitude – The relative amplitude from 0 to 1, multiplied with the envelope. Attach an
LFOhere for tremolo.bend – The pitch bend in octaves, from -12 to 12. A bend of 1/12 is a semitone. Attach an
LFOhere for vibrato or a sweep.waveform – A single cycle of signed 16-bit samples. The default is a square wave.
waveform_loop_start – The index where looping begins, from 0 to
len(waveform) - 1.waveform_loop_end – The index where looping ends, from
waveform_loop_start + 1tolen(waveform). Usewaveform_max_lengthto loop to the end whatever its length.envelope – The note’s envelope.
filter – A filter for the note’s output. Make it with a filter-making method for the synthesizer that will play the note, because coefficients depend on the sample rate.
ring_frequency – The ring modulator’s frequency in Hz. 0 turns ring modulation off. Both this and
ring_waveformmust be set for it to take effect.ring_bend – The pitch bend of the ring waveform, in octaves, from -12 to 12.
ring_waveform – The ring modulator’s waveform.
ring_waveform_loop_start – As
waveform_loop_start, for the ring waveform.ring_waveform_loop_end – As
waveform_loop_end, for the ring waveform.
- frequency
The base frequency of the note in Hz.
- filter
The filter applied to this note’s output, or None.
- panning
Where the note sits between the channels, from -1 (left) to 1 (right).
- amplitude
The relative amplitude from 0 to 1, multiplied with the envelope.
- bend
The pitch bend in octaves, from -12 to 12.
- waveform
The note’s waveform. Setting a buffer of a different size resets the note’s phase.
- waveform_loop_start
The index where looping begins, from 0 to
len(waveform) - 1.
- waveform_loop_end
The index where looping ends, from
waveform_loop_start + 1tolen(waveform).
- envelope
The note’s envelope, or None for the synthesizer’s.
- ring_frequency
The ring modulator’s frequency in Hz. 0 turns it off.
- ring_bend
The pitch bend of the ring waveform in octaves, from -12 to 12.
- ring_waveform
The ring modulator’s waveform. Setting a buffer of a different size resets the note’s phase.
- ring_waveform_loop_start
The index where looping of the ring waveform begins.
- ring_waveform_loop_end
The index where looping of the ring waveform ends.
- class synthio.Synthesizer(*, sample_rate=11025, channel_count=1, waveform=None, envelope=None)[source]
Bases:
objectA polyphonic synthesizer, played like any audio sample.
Notes are
Noteobjects or MIDI note numbers from 0 to 127, where 60 is middle C at about 262 Hz. A note given as a number uses the synthesizer’s waveform and envelope and has no tremolo or vibrato.- Parameters:
sample_rate – Frames per second, 1 or more. A higher rate takes more memory.
channel_count – 1 or 2.
waveform – A single cycle of signed 16-bit samples. The default is a square wave with a 50% duty cycle.
envelope – The envelope for notes that have none. The default of None turns notes on and off instantly.
- Raises:
ValueError –
sample_rateis below 1 orchannel_countis out of range.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- envelope
The envelope for all notes that have none. It can change while notes play, and then affects notes already playing.
- property pressed
The notes currently pressed. Notes in the release phase are not included.
- property blocks
Blocks to advance whether or not a playing note uses them, for free-running LFOs. The list cannot be replaced, but you can add to it and remove from it. It starts empty.
- property max_polyphony
How many notes can sound at once.
- property refused
How many presses were dropped because every channel was held. There is no stealing policy; this only counts. It includes presses that arrive through
audiopump.Events, and is not reset byrelease_all.
- press(press, /)[source]
Turn some notes on. Pressing a note that is already pressed has no effect.
- Parameters:
press – A note or a sequence of notes.
- release(release, /)[source]
Turn some notes off. Releasing a note that is not pressed has no effect.
- Parameters:
release – A note or a sequence of notes.
- change(release=(), press=(), retrigger=())[source]
Start notes, stop them and retrigger LFOs, all at once with respect to output generation.
Pressing a note that is already pressed returns it to the attack phase without resetting its amplitude. Releasing a note and pressing it again in the same call returns it to the attack phase from an amplitude of 0.
- Parameters:
release – Notes to turn off.
press – Notes to turn on.
retrigger – LFOs to retrigger.
- release_all_then_press(press, /)[source]
Turn off every playing note, then turn on the given notes. A note that was playing returns to the attack phase from an amplitude of 0.
- Parameters:
press – A note or a sequence of notes.
- note_info(note, /)[source]
Report a note’s envelope state.
- Returns:
(state, level)for a note that is playing here, including one in its release phase, and(None, 0.0)for one that is not.
- deinit()[source]
Release the synthesizer. Every later use raises
ValueError.
- class synthio.MidiTrack(buffer, tempo, *, sample_rate=11025, waveform=None, envelope=None)[source]
Bases:
objectPlays a stream of MIDI note events, as an audio sample.
Only note on and note off events are used; channels and velocities are ignored. Up to two notes may sound at once.
- Parameters:
buffer – The events, as stored in a MIDI file’s track chunk.
tempo – Ticks per second of the events.
sample_rate – Frames per second. A higher rate takes more memory.
waveform – A single cycle of signed 16-bit samples. The default is a square wave with a 50% duty cycle.
envelope – The envelope for notes. The default turns notes on and off instantly.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1.
- tempo
Ticks per second of the events.
- property error_location
The offset in bytes within the MIDI data of a decoding error, or None.
- deinit()[source]
Release the track. Every later use raises
ValueError.
- synthio.from_file(file, *, sample_rate=11025, waveform=None, envelope=None)[source]
Make a
MidiTrackfrom a MIDI file. Only single-track files (type 0) are supported.- Parameters:
file – A path, or a file already opened for reading in binary mode.
sample_rate – Frames per second. A higher rate takes more memory.
waveform – A single cycle of signed 16-bit samples. The default is a square wave with a 50% duty cycle.
envelope – The envelope for notes. The default turns notes on and off instantly.
- synthio.midi_to_hz(midi_note, /)[source]
Convert a MIDI note number to Hz, where 60 is middle C and 69 is concert A.
- synthio.voct_to_hz(ctrl, /)[source]
Convert a 1 volt per octave signal to Hz, where 2.0 (24/12) is middle C and 2.75 (33/12) is concert A.
- Raises:
ValueError –
ctrlis outside -11 to 11.
audiooscillator
Generated from audiooscillator.pyi; the file reads on its own.
A band-limited oscillator that other audio streams can steer.
Oscillator reads its pitch, linear FM, pulse width and hard sync from audio
streams every sample, so one oscillator can sync to another or be
frequency-modulated by it. synthio moves its pitch once per block and reads
a wavetable with no band limiting; this oscillator does neither. Steps are
band-limited with PolyBLEP and the triangle’s corners with PolyBLAMP.
- audiooscillator.SAW
a rising sawtooth. Waveforms add: pass
SAW + PULSEto mix the two from the same phase.- Type:
A waveform
- audiooscillator.PULSE
a pulse wave whose width is
pulse_width.- Type:
A waveform
- audiooscillator.TRIANGLE
a triangle.
- Type:
A waveform
- audiooscillator.SINE
a sine.
- Type:
A waveform
- class audiooscillator.Oscillator(*, sample_rate=48000, channel_count=1, buffer_size=None, frequency=Ellipsis, waveform=Ellipsis, waveform_right=Ellipsis, pulse_width=Ellipsis, level=Ellipsis, pitch_octaves=Ellipsis, fm_depth=Ellipsis, pwm_depth=Ellipsis, pitch=None, fm=None, pwm=None, sync=None)[source]
Bases:
objectA band-limited oscillator, played like any audio sample.
The output trails the phase by one sample, which lets a sync edge, which nothing can see coming, still correct the sample before it. The first block holds the waveform’s value at phase zero.
Every argument is a keyword. The inputs are audio samples, mono or stereo, read one frame per output frame; a stereo input is read from its first channel. An input that is left out or None does nothing.
- Parameters:
sample_rate – Frames per second, 1 or more.
channel_count – 1 or 2.
buffer_size – Bytes in one block, a whole number of frames, from one frame to 256 frames. The default is 256 frames.
frequency – The pitch in Hz before the
pitchinput moves it. The default is 440.0. The phase step is limited to between a tenth of a sample and just under half the rate.waveform – A sum of
SAW,PULSE,TRIANGLEandSINE. The default isSAW.waveform_right – The right channel’s waveform, from the same phase. The default is
SAW. Used only whenchannel_countis 2.pulse_width – The pulse’s width as a fraction of the cycle, 0.05 to 0.95. The default is 0.5.
level – The output for a waveform’s full swing, where 1.0 is full scale. The default is 1.0.
pitch_octaves – Octaves the
pitchinput moves the pitch for a full-scale signal. The default is 10.0.fm_depth – Hz the
fminput moves the frequency for a full-scale signal, linearly. The default is 0.0.pwm_depth – Pulse width the
pwminput adds for a full-scale signal. The default is 0.5.pitch – An audio sample that moves the pitch exponentially.
fm – An audio sample that frequency-modulates the oscillator.
pwm – An audio sample that modulates the pulse width.
sync – An audio sample that resets the phase when it rises through zero.
- Raises:
TypeError – An unknown keyword was given, or an input is not an audio sample.
ValueError –
sample_rateis below 1,channel_countis not 1 or 2,buffer_sizeis not valid, or an input has more than two channels.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- set(*, frequency=Ellipsis, waveform=Ellipsis, waveform_right=Ellipsis, pulse_width=Ellipsis, level=Ellipsis, pitch_octaves=Ellipsis, fm_depth=Ellipsis, pwm_depth=Ellipsis)[source]
Change options while the oscillator plays. The options are those of the constructor, and all of them change together or not at all.
- Raises:
TypeError – An unknown option was given.
- modulate(*, pitch=Ellipsis, fm=Ellipsis, pwm=Ellipsis, sync=Ellipsis)[source]
Connect or disconnect input streams while the oscillator plays. Inputs you do not name stay as they are; pass None to disconnect one.
- Raises:
TypeError – An unknown input was named, or one is not an audio sample.
ValueError – An input has more than two channels.
- deinit()[source]
Release the oscillator and let go of its inputs. Every later use raises
ValueError.
audiomodal
Generated from audiomodal.pyi; the file reads on its own.
A bank of resonators, which is what a struck object is.
A drum head, a marimba bar, a bell or a wine glass rings as a sum of decaying
sinusoids at frequencies that are not harmonics of anything. Give Bank that
list of modes and a short noise burst for the stick, and it is that object.
- audiomodal.FRAMES
- Type:
Frames in one block
- audiomodal.MAX_MODES
- Type:
The most modes a bank can have
- audiomodal.MIN_DECAY_MS
- Type:
The shortest decay a mode takes, in milliseconds
- audiomodal.MAX_DECAY_MS
- Type:
The longest decay a mode takes, in milliseconds
- class audiomodal.Bank(*, modes=8, sample_rate=48000, channel_count=2, mix=Ellipsis, gain=Ellipsis)[source]
Bases:
objectA bank of resonators, played like any audio sample.
The bank is fed a stimulus with
play, usually a short noise burst, and rings at the modes you set. The tail keeps ringing after the stimulus stops, because a drum whose decay ended the instant the stick left would be the one thing this node exists not to be.A new bank has no modes set, so with the default
mixof 1.0 it is silent, not a passthrough. Usemix=0.0for the untouched signal.Every argument is a keyword.
modes,sample_rateandchannel_countfix the allocation, so they can only be given here.- Parameters:
modes – How many resonators, 1 to
MAX_MODES. The default is 8.sample_rate – Frames per second.
channel_count – 1 or 2.
mix – How much of the ringing replaces the dry signal, 0.0 to 1.0, clamped. The default is 1.0.
gain – Output gain, 0.0 to 16.0, clamped. The default is 1.0.
- Raises:
ValueError –
modesis out of range orchannel_countis not 1 or 2.TypeError – An unknown keyword was given.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- property modes
How many modes the bank holds.
- property ringing
Whether any mode still holds energy. This is exact, not a threshold, so a voice allocator can ask whether a drum has stopped.
- set_mode(index, frequency, decay, gain, /)[source]
Place one mode.
- Parameters:
index – The mode, 0 up to
modes - 1.frequency – The mode’s frequency in Hz, clamped just below half the sample rate.
decay – The time the mode takes to fall by 60 dB, in seconds, from 0.001 to 30.0. This is not a Q.
gain – The peak of the mode’s impulse response, from -16.0 to 16.0. A modal table read out of a paper goes in as published.
- Raises:
IndexError –
indexis out of range.
- set_modes(table, /)[source]
Place the whole list of modes in one call.
- Parameters:
table – Rows of
(frequency, decay, gain), as forset_mode, placed from mode 0. A table shorter than the bank silences the rest, so a shorter table is a smaller drum and not a chord of two.- Raises:
ValueError – The table has more rows than the bank has modes, or a row is not three values.
- set(*, mix=Ellipsis, gain=Ellipsis)[source]
Change options while the bank plays, without stopping anything ringing. All of them change together or not at all.
- Parameters:
mix – As for the constructor.
gain – As for the constructor.
- Raises:
TypeError – An unknown option was given.
- deinit()[source]
Release the bank and let go of its stimulus. Every later use raises
ValueError.
audiosampler
Generated from audiosampler.pyi; the file reads on its own.
Recorded notes, played at any pitch.
Sampler is an audio source with a fixed number of voices. A voice plays a
recording of a note at any pitch, loops a region of it while the key is held,
and lets the rest out when the key lifts, under an amplitude envelope with an
optional resonant low-pass filter, a modulation envelope and two LFOs. That
is what a SoundFont instrument and a drum machine need, and what
audiomixer.Mixer (which plays sources at their own rate) and synthio
(which plays single-cycle waveforms) cannot do.
SampleBuffer holds samples in memory outside the collected heap, so a bank
of many megabytes does not slow every garbage collection.
All voices are mixed in one C call per block, through a 4-point Hermite interpolator.
- audiosampler.FRAMES
- Type:
Frames in one block when
buffer_sizeis not given
- audiosampler.MAX_FRAMES
- Type:
The most frames in one block
- audiosampler.LOOP_NONE
play to the end of the buffer and stop. This is SoundFont’s
sampleModesvalue 0.- Type:
A loop mode
- audiosampler.LOOP_FOREVER
loop
[loop_start, loop_end)untilSamplerVoice.releaseorSamplerVoice.stop. This is SoundFont’ssampleModesvalue 1.- Type:
A loop mode
- audiosampler.LOOP_UNTIL_RELEASE
loop while the key is held, then play on past the loop to the end of the buffer. This is SoundFont’s
sampleModesvalue 3.- Type:
A loop mode
- class audiosampler.SampleBuffer(size, /)[source]
Bases:
objectZeroed memory for samples, outside the collected heap.
Read audio into it, or copy it in, and play views of it with
SamplerVoice.play. The memory comes from PSRAM on boards whose audio driver says where, and from the system allocator elsewhere.A
memoryviewof a buffer does not keep it alive. Hold the buffer itself for as long as a voice plays from it.- Parameters:
size – Bytes to allocate and zero.
- Raises:
ValueError –
sizeis negative.MemoryError – The bytes could not be allocated.
- class audiosampler.SamplerVoice[source]
Bases:
objectOne voice of a
Sampler.Get voices from
Sampler.voice; they cannot be made on their own. A voice plays one note at a time. Starting a new note on a sounding voice fades the old one out over 5 ms.- level
The voice’s level, where 1.0 is unity gain. It is limited to 0.0 to 1.0 when applied, and reads back as you set it. A live setting: the change lands at the next block, as a ramp across it, so a fader move does not click.
- pan
Position in the stereo field from -1.0 (left) to 1.0 (right), limited to that range when applied. A live setting, ramped like
level.
- pitch
Playback speed as a ratio, 1.0 for the recording’s own pitch, from 1/64 to 64 (clamped). A live setting, which is how a pitch bend is played.
- cutoff
The low-pass filter’s cutoff in Hz, or None for no filter. A live setting: a change lands within 32 frames, and a filter switched on starts from rest.
- vibrato_depth
The vibrato LFO’s depth in cents. A live setting, so a mod wheel is a series of writes here; each lands within 32 frames.
- property playing
Whether the voice still sounds.
- play(buffer, *, rate=None, pitch=None, loop_start=0, loop_end=None, loop_mode=0, level=None, pan=None, delay=None, attack=None, hold=None, decay=None, sustain=None, release=None, cutoff=None, resonance=None, mod_delay=None, mod_attack=None, mod_hold=None, mod_decay=None, mod_sustain=None, mod_release=None, mod_to_pitch=None, mod_to_cutoff=None, vibrato_delay=None, vibrato_rate=None, vibrato_depth=None, lfo_delay=None, lfo_rate=None, lfo_to_pitch=None, lfo_to_cutoff=None, lfo_to_volume=None)[source]
Start a note.
The buffer is held for as long as the voice sounds and let go when it stops. The step per output frame is
pitch * rate / sample_rate, so a 44.1 kHz recording plays at the right speed through a 48 kHz output without being told anything else.Every option except
bufferis a keyword, and None (the default) means the value given here.- Parameters:
buffer – The recording: mono signed 16-bit samples, in a buffer holding at least one whole sample.
rate – The recording’s own sample rate in Hz. The default is the sampler’s.
pitch – Playback speed as a ratio. The default is 1.0.
loop_start – The first frame of the loop.
loop_end – The frame after the last one of the loop. The default is the end of the buffer.
loop_mode –
LOOP_NONE,LOOP_FOREVERorLOOP_UNTIL_RELEASE.level – Level from 0.0 to 1.0, where 1.0 is unity gain. The default is 1.0.
pan – Stereo position, -1.0 to 1.0. The default is 0.0.
delay – Seconds before the sound starts, which is what a flam wants. The default is 0.0.
attack – Amplitude envelope attack time in seconds. The default is 0.0.
hold – Amplitude envelope hold time in seconds. The default is 0.0.
decay – Amplitude envelope decay time in seconds. The default is 0.0.
sustain – Amplitude envelope sustain level, linear. The default is 1.0.
release – Amplitude envelope release time in seconds. The default is 0.0.
cutoff – Low-pass cutoff in Hz. A cutoff of 19.9 kHz or more, with no resonance and nothing moving it, is no filter at all, and so is leaving it out.
resonance – The filter’s response at the cutoff above its response at DC, in dB, from 0 to 96. DC drops by half of it, as the SoundFont specification puts it. 0 is a Butterworth.
mod_delay – The modulation envelope’s delay in seconds. This envelope has the amplitude envelope’s six stages and moves pitch and cutoff. The default is 0.0.
mod_attack – Its attack time in seconds. The default is 0.0.
mod_hold – Its hold time in seconds. The default is 0.0.
mod_decay – Its decay time in seconds. The default is 0.0.
mod_sustain – Its sustain level, linear. The default is 1.0.
mod_release – Its release time in seconds. The default is 0.0.
mod_to_pitch – How far the modulation envelope moves the pitch at full scale, in cents. The default is 0.0.
mod_to_cutoff – How far it moves the cutoff at full scale, in cents. The default is 0.0.
vibrato_delay – Seconds before the vibrato LFO starts. The default is 0.0.
vibrato_rate – The vibrato LFO’s rate in Hz. The default is 0.0.
vibrato_depth – The vibrato LFO’s depth in cents, moving the pitch. The default is 0.0.
lfo_delay – Seconds before the modulation LFO starts. The default is 0.0.
lfo_rate – The modulation LFO’s rate in Hz. The default is 0.0.
lfo_to_pitch – How far the modulation LFO moves the pitch at its peak, in cents. The default is 0.0.
lfo_to_cutoff – How far it moves the cutoff at its peak, in cents. The default is 0.0.
lfo_to_volume – How far it moves the level at its peak, in dB. The default is 0.0.
- Raises:
ValueError –
bufferholds less than one whole 16-bit sample,loop_startorloop_endis negative,loop_modeis not one of the three, the loop does not fit the buffer, or the sampler was deinitialised.
- release()[source]
Let the key go: enter the release stage from wherever the envelope is. In
LOOP_UNTIL_RELEASEthe voice also stops looping and plays on to the end.
- class audiosampler.Sampler(*, voice_count=8, buffer_size=0, channel_count=2, bits_per_sample=16, samples_signed=True, sample_rate=48000)[source]
Bases:
objectA bank of sample-playing voices, played like any audio sample.
The output is signed 16-bit. Notes start on
voice.- Parameters:
voice_count – How many voices, 1 to
MAX_VOICES.buffer_size – Bytes in one block, a whole number of frames up to
MAX_FRAMES. 0 meansFRAMESframes.channel_count – 1 or 2.
bits_per_sample – Only 16 is accepted. The argument exists so a sampler can stand where a mixer stood.
samples_signed – Only True is accepted, for the same reason.
sample_rate – Frames per second, 1 or more.
- Raises:
ValueError – An argument is out of range, or
bits_per_sampleorsamples_signedasks for anything but signed 16-bit.
- sample_rate
Frames per second. Writable, to 1 or more.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- property voice
The voices, as a tuple of
voice_countSamplerVoiceobjects.
- property voice_count
How many voices the sampler has.
- property playing
Whether any voice sounds, a stopped note’s fade included.
- stop()[source]
Stop every voice, each with the 5 ms fade of
SamplerVoice.stop.
- deinit()[source]
Stop every voice and let go of every buffer. Every later use raises
ValueError.
audiograph
Generated from audiograph.pyi; the file reads on its own.
A whole patch rendered by one C call per block.
Graph renders a patch in one C call per block. You build it once, from nodes
that call the kernels audiodsp already has (the oscillator, the ladder, the
float biquad, the feedback delay, the all-pass cascade, the sample-and-hold)
and a few small ones a voice needs (an envelope, an LFO, noise, a mixer, a
VCA, a glide, a clipping two-pole filter, an overdrive and more), then call
Graph.run once a block. Nothing in Python runs between the nodes, which is
what lets a six-voice polysynth play in real time on an ESP32-P4. It is the
same C on CPython, MicroPython and CircuitPython, so a patch built and
listened to on the desktop renders the same samples on the board.
Example:
import audiograph as ag
g = ag.Graph(sample_rate=48000, frames=128, channel_count=2)
pitch, gate, env, saw, vcf, out = (g.buffer() for _ in range(6))
g.add(ag.CONST, 0, (), pitch) # the key, in octaves from C4
key = g.add(ag.CONST, 0, (), gate)
g.add(ag.ENV, 0, (gate,), env)
osc = g.add(ag.OSC, 0, (pitch, None, None, None), saw)
g.set(osc, ag.OSC_WAVEFORM, 1) # a sawtooth
lad = g.add(ag.LADDER, 0, (saw, env), vcf) # the envelope sweeps the cutoff
g.set(lad, ag.LADDER_CUTOFF_HZ, 600.0)
g.add(ag.VCA, 0, (vcf, env, None), out)
g.add(ag.OUT, ag.ALWAYS, (out, out), None)
pcm = bytearray(128 * 2 * 2)
g.set(key, 0, ag.UNIT) # key down
sounding = g.run(pcm, 0) # one block into pcm
A graph owns buffers blocks of frames signed 16-bit samples and a
table of up to nodes nodes. Every node reads some buffers, writes one,
belongs to a group and holds one kernel’s settings behind up to sixteen float
parameters. Nodes run in the order you added them, so add a node after the
nodes it reads. Every node is mono; a stereo patch has two buffers where it
needs them. A block is 256 frames at most, a node has at most eight inputs
and a group is 0 to 31 or ALWAYS. A graph refuses a node with nothing to
write (every kind but OUT writes a buffer), an input or output id past its
buffers, and a node past its table.
The buffers carry one wire: UNIT counts is 1.0, the +10 V of a modular rack,
so audio at 0.5 is a quarter of full scale.
An input left None is open: an oscillator without a pitch input plays
OSC_FREQUENCY, a ladder without a cutoff input sits at LADDER_CUTOFF_HZ.
The kernel nodes take their parameters under the same numbers as the modules
that wrap them (audiooscillator, audioladder, audiobiquad, audioecho,
and audiobiquad.AllPass for PHASER), re-exported here so a caller needs
no other module.
Every node kind and every parameter index is a constant below; a kind’s parameters carry its name as a prefix.
- audiograph.CONST
writes the value of parameter 0, in counts, every sample.
- Type:
A node kind with no inputs
- audiograph.OSC
pitch, fm, pwm, sync.
- Type:
A band-limited oscillator,
audiooscillator’s. Inputs
- audiograph.LADDER
audio, cutoff.
- Type:
A transistor ladder filter,
audioladder’s, with the cutoff input read every sample. Inputs
- audiograph.BIQUAD
audio.
- Type:
A float biquad,
audiobiquad.Biquad’s, which walks to new coefficients. Input
- audiograph.FBDELAY
audio.
- Type:
A feedback delay,
audioecho.FeedbackDelay’s. Built withargthe line’s length in milliseconds.Graph.tablesets its wow shape. Input
- audiograph.ENV
gate.
- Type:
An ADSR envelope from 0 to
UNIT; each stage is a one-pole approach, the attack aimed past 1.0 so it arrives with a slope. Input
- audiograph.LFO
A low-frequency oscillator of one of five shapes, swinging plus and minus its amplitude. No inputs.
- audiograph.NOISE
White noise. Parameter 0 is the amplitude in counts. No inputs.
- audiograph.MIX
A mixer of up to eight inputs. Parameters 0 to 7 are a gain per input, and
MIX_OFFSETadds an offset. A gain that moved ramps across the block.
- audiograph.VCA
audio times the chosen control input over
UNIT, times the gain. Inputs: audio, cv_a, cv_b.- Type:
A voltage-controlled amplifier
- audiograph.OUT
interleaved stereo, or the mean when the graph is mono. Parameter 0 is a scale. Inputs: left, right. It writes no buffer, so its output is None.
- Type:
Writes the run’s output buffer
- audiograph.PHASER
first-order all-pass stages, one feedback around the chain, and a dry and wet mix. Built with
argthe number of stages (0 means 4). Input: audio.- Type:
audiobiquad.AllPasson one channel
- audiograph.LAG
note, pitch, legato.
- Type:
Glides a note’s pitch CV to each new note, with the bend (pitch minus note) on top. Inputs
- audiograph.SAMPLE_HOLD
signal, clock.
- Type:
Holds its signal at each rising edge of the clock, or
SH_RATEtimes a second with the clock open. Inputs
- audiograph.TWOPOLE
audio, cutoff CV.
- Type:
A 12 dB per octave filter with its nonlinearity inside the feedback loop. Inputs
- audiograph.OVERDRIVE
audio.
- Type:
audiofilters.Distortion’s soft-clipped overdrive followed by a high shelf at 1.5 kHz. CircuitPython’s ownaudiographlacks it; check withhasattr. Input
- audiograph.TANH
audio.
- Type:
TANH_LEVEL * tanh(TANH_DRIVE * x)withxin units ofUNIT. The same bytes on every interpreter. Input
- audiograph.PAN
the left side goes to the node’s output and the right to the buffer given as
argwhen the node is added. Parameters 0 to 7 are a gain per input, andPAN_PANplusiis inputi’s pan.- Type:
A stereo mixer of up to eight inputs with a balance on each
- audiograph.WAVEFOLD
three sine folds crossfaded with the input by the fold. Inputs: audio, fold CV.
- Type:
A West Coast wavefolder
- audiograph.LPG
audio, control, strike.
- Type:
A vactrol low-pass gate. Inputs
- audiograph.MODAL
bells, bars and drum heads,
audiomodal.Bank’s kernel. Inputs: excitation, strike.- Type:
Eight tuned resonators struck or rung by the input
- audiograph.STRUCK
strike, velocity.
- Type:
A hammer or pluck exciter into a 24-mode struck bar bank, for tine, reed, vibraphone and clavinet voices.
Graph.tablereplaces its modes. Inputs
- audiograph.PICKUP
audio.
- Type:
An electric piano pickup’s asymmetric nonlinearity with DC removal. Input
- audiograph.TREMOLO
audio, rate CV, depth CV.
- Type:
A mono-to-stereo auto-pan or amplitude tremolo. Built with
argthe right side’s buffer, likePAN. Inputs
- audiograph.DECAY
trigger, velocity.
- Type:
A one-shot exponential envelope, a burst of re-strikes, or the two-stage, soft-attack and rise shapes a drum needs.
Graph.tablesets the strikes. Inputs
- audiograph.PINK
Paul Kellet’s pinking filter on a white input. Input: white.
- Type:
Pink noise
- audiograph.CRUSH
audio.
- Type:
Rounds the audio to a number of bits. Input
- audiograph.ACID
audio, env, accent.
- Type:
A diode ladder filter with an accent circuit, as a TB-303 style bass line needs. Inputs
- audiograph.SPRING
audio.
- Type:
A two-tank spring reverb over
audiofreeverb, mixed on both sides. Built withargthe right side’s buffer. Input
- audiograph.ADSR2
gate.
- Type:
An
ENVcontour that starts atADSR2_INITIALand peaks atADSR2_ATTACK_LEVEL. Input
- audiograph.GLISS
note, pitch, legato.
- Type:
LAG’s linear glide stepped onto a semitone grid once a block. Inputs
- audiograph.FOLLOW
audio.
- Type:
An envelope follower, one level a block, peak or RMS. Input
- audiograph.WAVETABLE
pitch, gate and an extra signal added before the contacts.
Graph.tableholds the cycle;argis the most samples it may hold.- Type:
A drawbar organ voice from one stored cycle. Inputs
- audiograph.ROTARY
argis the right side’s buffer. Input: audio.- Type:
A rotary speaker, stereo like
PAN
- audiograph.ALWAYS
A group that always runs, whatever mask
Graph.runis given. Pass it as a node’sgroup.
- audiograph.UNIT
A buffer holds 16-bit samples, so audio at 0.5 is a quarter of full scale.
- Type:
The wire’s 1.0 in counts
- audiograph.DECAY_RESTRIKE
with a strike table, seconds to fall by 40 dB between spikes.
- Type:
DECAYparameter
- audiograph.DECAY_ATTACK
seconds of linear ramp from 0 up to the velocity before the fall begins.
- Type:
DECAYparameter
- audiograph.DECAY_FAST
seconds to fall by 40 dB for the first
DECAY_FAST_SECseconds, thenDECAY_DECAYfor the rest.- Type:
DECAYparameter
- audiograph.DECAY_RISE
seconds to fall by 40 dB of a second envelope that is subtracted from the first.
- Type:
DECAYparameter
- audiograph.DECAY_STRIKES
- Type:
The most strikes
Graph.tabletakes for aDECAYnode
- audiograph.LFO_SHAPE
one of the
LFO_*shapes. Every shape comes from one phase, so LFOs of different shapes at one rate stay in step.- Type:
LFOparameter
- audiograph.LFO_TRIANGLE
a triangle whose bottom is at the start of the cycle.
- Type:
An
LFO_SHAPEvalue
- audiograph.LFO_SQUARE
plus the amplitude for the first half of the cycle, minus for the second.
- Type:
An
LFO_SHAPEvalue
- audiograph.LFO_RANDOM
a new level, uniform in plus and minus the amplitude, at the start of each cycle, held until the next.
- Type:
An
LFO_SHAPEvalue
- audiograph.VCA_CURVE
VCA_LINEARorVCA_EXPONENTIAL.- Type:
VCAparameter
- audiograph.LAG_SHAPE
LAG_LINEAR(the default) orLAG_ONE_POLE.- Type:
LAGparameter
- audiograph.LAG_AUTO
glide only when the legato input is above 0.5 at the start of the block.
- Type:
A
LAG_MODEvalue
- audiograph.LAG_LINEAR
a straight line that takes
LAG_TIMEseconds wherever it starts from.- Type:
A
LAG_SHAPEvalue
- audiograph.GLISS_STEP
the grid the pitch is stepped onto, where 0.1 is a semitone at one volt per octave.
- Type:
GLISSparameter
- audiograph.SH_LAG
a per-sample one-pole coefficient from 0 to 1 that slews the output toward the held value. 0 does not slew.
- Type:
SAMPLE_HOLDparameter
- audiograph.SH_RATE
with the clock input open, how many times a second to refresh.
- Type:
SAMPLE_HOLDparameter
- audiograph.TWOPOLE_DEPTH
how far the cutoff CV moves the cutoff; 1 is an octave per 1638.4 counts, 0 ignores the input.
- Type:
TWOPOLEparameter
- audiograph.TWOPOLE_RESONANCE
the Sallen-Key’s peak or the CMOS filter’s resonance, 0.0 to 1.0.
- Type:
TWOPOLEparameter
- audiograph.TWOPOLE_SK_LOWPASS
a Sallen-Key low-pass whose peak feedback runs through a diode clipper.
- Type:
A
TWOPOLE_TYPEvalue
- audiograph.TWOPOLE_SK_HIGHPASS
a Sallen-Key high-pass.
- Type:
A
TWOPOLE_TYPEvalue
- audiograph.TWOPOLE_CMOS_LOWPASS
a CMOS state-variable low-pass, with a clipping inverter in every stage.
- Type:
A
TWOPOLE_TYPEvalue
- audiograph.TWOPOLE_CMOS_BANDPASS
the CMOS filter as a band-pass.
- Type:
A
TWOPOLE_TYPEvalue
- audiograph.TWOPOLE_CMOS_HIGHPASS
the CMOS filter as a high-pass.
- Type:
A
TWOPOLE_TYPEvalue
- audiograph.OVERDRIVE_TONE
the shelf’s gain, 0.0 to 1.0, from minus 12 dB through flat at 0.5 to plus 12 dB.
- Type:
OVERDRIVEparameter
- audiograph.OVERDRIVE_LEVEL
the linear gain after the clipper; 1 is unity.
- Type:
OVERDRIVEparameter
- audiograph.PAN_PAN
the index of the first pan; input
i’s pan isPAN_PAN + i, from -1 (left) to 1 (right).- Type:
PANparameter
- audiograph.WAVEFOLD_FOLD
how far the signal is folded, 0.0 to 1.0. A fold CV adds to it.
- Type:
WAVEFOLDparameter
- audiograph.LPG_MANUAL
a manual opening, 0.0 to 1.0, added to the control and strike inputs.
- Type:
LPGparameter
- audiograph.LPG_VCF
low-pass the input at a cutoff the vactrol moves, 30 Hz closed to 12 kHz open.
- Type:
An
LPG_MODEvalue
- audiograph.LPG_BOTH
filter and scale, so the highs die before the lows.
- Type:
An
LPG_MODEvalue, and the default
- audiograph.PICKUP_MODE
PICKUP_ELECTROMAGNETICorPICKUP_ELECTROSTATIC.- Type:
PICKUPparameter
- audiograph.PICKUP_OFFSET
a shift added before the nonlinearity; above 0 it grows second-harmonic bark.
- Type:
PICKUPparameter
- audiograph.PICKUP_ELECTROMAGNETIC
a Rhodes-style coil.
- Type:
A
PICKUP_MODEvalue, and the default
- audiograph.PICKUP_ELECTROSTATIC
a Wurlitzer-style reed plate.
- Type:
A
PICKUP_MODEvalue
- audiograph.ACID_ENVMOD
how far the envelope input moves the cutoff, 0.0 to 1.0.
- Type:
ACIDparameter
- audiograph.MODAL_MIX
from the excitation alone (0.0) to the bank alone (1.0).
- Type:
MODALparameter
- audiograph.MODAL_RATIO
the index of the first mode ratio; mode
msits at the frequency timesMODAL_RATIO + m, form0 to 7. A ratio of 0 turns its mode off.- Type:
MODALparameter
- audiograph.STRUCK_HARDNESS
0.0 to 1.0; harder shortens the strike’s pulse while keeping its area.
- Type:
STRUCKparameter
- audiograph.STRUCK_SHAPE
STRUCK_HAMMERorSTRUCK_PLUCK.- Type:
STRUCKparameter
- audiograph.STRUCK_HAMMER
a half-sine pulse.
- Type:
A
STRUCK_SHAPEvalue
- audiograph.STRUCK_PLUCK
a rising ramp.
- Type:
A
STRUCK_SHAPEvalue
- audiograph.STRUCK_MODES
- Type:
The most modes
Graph.tabletakes for aSTRUCKnode
- audiograph.TREMOLO_DEPTH
the depth, 0.0 to 1.0. A change glides across the next block.
- Type:
TREMOLOparameter
- audiograph.TREMOLO_MODE
TREMOLO_PANorTREMOLO_AMPLITUDE.- Type:
TREMOLOparameter
- audiograph.TREMOLO_PAN
stereo auto-pan.
- Type:
A
TREMOLO_MODEvalue, and the default
- audiograph.TREMOLO_AMPLITUDE
the same amplitude tremolo on both sides.
- Type:
A
TREMOLO_MODEvalue
- audiograph.FOLLOW_PEAK
follow the peak.
- Type:
A
FOLLOW_MODEvalue
- audiograph.FOLLOW_RMS
follow the RMS level.
- Type:
A
FOLLOW_MODEvalue
- audiograph.ROTARY_SPEED
ROTARY_STOP,ROTARY_SLOWorROTARY_FAST.- Type:
ROTARYparameter
- audiograph.ROTARY_STOP
the rotors stopped.
- Type:
A
ROTARY_SPEEDvalue
- audiograph.ROTARY_SLOW
the slow speed.
- Type:
A
ROTARY_SPEEDvalue
- audiograph.ROTARY_FAST
the fast speed.
- Type:
A
ROTARY_SPEEDvalue
- audiograph.OSC_WAVEFORM
1 for a sawtooth, 2 pulse, 4 triangle, 8 sine; a sum plays those added.
- Type:
OSCparameter
- audiograph.LADDER_RESONANCE
0 to 4.2; at 4 it sustains a tone at the cutoff.
- Type:
LADDERparameter
- audiograph.LADDER_PASSBAND_COMP
0.0 to 1.0, how much of the passband to give back.
- Type:
LADDERparameter
- audiograph.BIQUAD_MODE
a mode numbered as
audiobiquadnumbers them.- Type:
BIQUADparameter
- audiograph.BIQUAD_GAIN_DB
the gain in decibels, for the peaking and shelf modes.
- Type:
BIQUADparameter
- audiograph.BIQUAD_RAMP
milliseconds the filter takes to walk to new coefficients, 0 to 1000; the default is 20. The walk is the power of two frames nearest the request, and 0 is one frame. Set it low when a value moves every block.
- Type:
BIQUADparameter
- audiograph.PHASER_FREQUENCY
the frequency in Hz at which one stage’s phase passes minus 90 degrees.
- Type:
PHASERparameter
- class audiograph.Graph(*, sample_rate=48000, frames=128, channel_count=2, buffers=64, nodes=64, queue=0)[source]
Bases:
objectA patch of nodes that renders a block at a time.
Every argument is a keyword.
A
Graphis also an audio source: hand it to an output, a mixer or the pump and each pull renders one block, and it never ends.set,resetandenabledo not touch the running graph. Each goes into the queue, and the renderer applies everything waiting at the top of the next block it renders, so a change never lands halfway through a block. Betweenholdandcommitnothing is released, so a batch lands on one block together. When the queue fills, the control side waits for the pump to finish its block and applies what is waiting itself, so nothing is dropped; a held batch that overflowed lands across two blocks.While the pump is pulling a graph, the calls that change its shape (
buffer,add,tableandwrite) and arunof your own raiseRuntimeError. Build the graph before you hand it over.readandpeakstill work, but can catch a buffer the pump is rendering into.- Parameters:
sample_rate – The patch’s rate in Hz, 1 or more. The default is 48000.
frames – Frames in a block, 1 to 256. The default is 128.
channel_count – Channels of the output, 1 or 2.
buffers – How many block buffers the graph owns, 1 to 4096. The default is 64.
nodes – How many nodes the table holds, 1 to 4096. The default is 64.
queue – How many changes the control queue holds, 1 to 65536. The default, 0, is the larger of 256 and four per node.
- Raises:
ValueError – An argument is out of range.
- sample_rate
Frames per second, as given to the constructor.
- property bits_per_sample
Size of one sample in bits: always 16.
- property channel_count
Number of channels: 1 or 2.
- buffer()[source]
Hand out a fresh block buffer.
- Returns:
- Raises:
ValueError – No buffers are left.
RuntimeError – The pump is rendering this graph.
- add(kind, group, inputs, output, arg=0.0, /)[source]
Append a node.
Nodes run in the order you add them, so add a node after the nodes it reads.
- Parameters:
kind – A node kind, such as
OSC.group – 0 to 31, or
ALWAYS.runskips a node whose group bit is not set in itsenablemask, and a node skipped after it ran zeroes its output once.inputs – Buffer ids the node reads, up to eight. None is an open input.
output – The buffer id the node writes. Every kind but
OUTneeds one.arg – A setting fixed at construction. What it means depends on the kind: the line’s length for
FBDELAY, the stages forPHASER, the right side’s buffer forPAN,TREMOLO,SPRINGandROTARY.
- Returns:
The node’s index.
- Raises:
ValueError – The kind is unknown, the group is out of range, there are too many inputs, a buffer id is out of range, the node has no output, or the graph is full.
RuntimeError – The pump is rendering this graph.
- set(node, index, value, /)[source]
Store a parameter. The change is queued and lands at the top of the next block. A parameter that has not changed costs nothing per block.
- Parameters:
node – The node’s index.
index – The parameter, such as
OSC_WAVEFORM, or a number for a kind that numbers its parameters from 0.value – The new value.
- Raises:
ValueError – The node or parameter does not exist.
- get(node, index, /)[source]
The value
setlast stored, whether or not a block has heard it.- Raises:
ValueError – The node or parameter does not exist.
- table(node, table, /)[source]
Give a node a table.
What the table is depends on the node. For
FBDELAYit is the wow shape, anarray('h')the graph keeps a reference to and does not copy. ForSTRUCKit is up toSTRUCK_MODES(ratio, decay, gain)triples, or a flat float array of three floats a mode. ForDECAYit is up toDECAY_STRIKES(delay in seconds, level)pairs, or a flat float array of two floats a strike. ForWAVETABLEit is one cycle, anarray('h')of 2 samples up to the node’sarg. A copied table may change while the pump plays; a borrowed one may not.For
STRUCK, setSTRUCK_FREQUENCYfirst and then call this: it retunes the bank at the frequency you last set, so the block that plays the note only copies the result.- Raises:
TypeError – The table is not of the type the node takes.
ValueError – The node takes no table, or the table is too long.
RuntimeError – The pump is rendering this graph (not for tables the node copies).
- reset(node, /)[source]
Clear a node’s running state. Queued, like
set.- Raises:
ValueError – The node does not exist.
- carry(node, src_graph, src_node, /)[source]
Take over a node’s running state from a node of another graph, or of this one: its voice, envelope, oscillator phase, filter memory and delay line continue where
src_nodeleft them. Build the changed patch beside the running one, carry the nodes both have, thenswapit in. Do it between two blocks.- Parameters:
node – The node of this graph that receives the state.
src_graph – The graph the state comes from.
src_node – The node in
src_graph.
- Raises:
ValueError – The nodes are of different kinds, were built with different
argvalues, hold state of different sizes, or belong to graphs at different sample rates. A node it refuses keeps the fresh state it was built with.RuntimeError – The pump is rendering this graph; park it first.
- swap(other, /)[source]
Trade patches with
otheron a block boundary: nodes, buffers, wiring and queue. This graph keeps its identity and its frame count, so what holds it (the pump, an output, a mixer) need not know, and rendersother’s patch from the next block on.otheris left holding the old patch, ready to drop. Node ids are then the ones you got from buildingother.- Raises:
ValueError – The graphs differ in sample rate, block size or channel count.
- enable(mask, /)[source]
Set the groups a pull renders, as a bit mask. Queued like
set, so a note’s gate and its group’s enable land in the same block.
- hold()[source]
Stop releasing queued changes until
commit, so a batch (a patch change, a chord) lands on one block together.
- sounding()[source]
What the renderer last published.
- Returns:
(sounding, frame, applied, pushed)– the mask of groups still sounding after the last block, the frames rendered so far, and the number of changes applied and queued. A change counted inpushedand not yet inappliedhas not been heard. Readsoundingandframetogether and you know which block the mask belongs to.
- stats()[source]
The queue’s counts.
- Returns:
A dict with
capacity,pushed,applied,overflows(times the queue filled),splits(held batches that landed across two blocks),high_water(the most changes waiting at once) andframe. Size the queue for your biggest batch andoverflowsandsplitsstay 0.
- run(out=None, block=0, enable=4294967295, /)[source]
Render one block, draining the queue first.
Runs every node whose group bit is set in
enableand everyALWAYSnode.- Parameters:
out – Where the
OUTnode writes: interleaved signed 16-bit samples,frames * channel_countof them a block. None renders without keeping the output.block – Which block of
outto fill, counting from 0, so one buffer holds several blocks.enable – The groups to run, a bit mask. The default runs all.
- Returns:
The mask of groups whose envelopes are still sounding. When a voice’s amplitude envelope goes idle, the mask tells you to park its group.
- Raises:
ValueError –
outis too small for that block.RuntimeError – The pump is rendering this graph.
- peak(buffer, /)[source]
The peak of a buffer’s block, as a count.
- Raises:
ValueError – The buffer id does not exist.
- read(buffer, dst, /)[source]
Copy a buffer’s block out into
dst, which must hold exactly one block offramessigned 16-bit samples.- Raises:
ValueError – The buffer id does not exist, or
dstis the wrong size.
- write(buffer, src, /)[source]
Fill a buffer’s block from
src, exactly one block offramessigned 16-bit samples, so Python can feed a buffer from something the graph has no node for.- Raises:
ValueError – The buffer id does not exist, or
srcis the wrong size.RuntimeError – The pump is rendering this graph.