Generate PCM from Python¶
Submediant performs offline synthesis. You can compose a score, select an instrument and render samples entirely from Python, without a CLI subprocess, prerecorded audio, Pillow, or FFmpeg. Install the package as described in Installation and runtime. Run the examples below from the repository root.
Choose the API for the data you own¶
New notes and instruments:
submediant.MusicalSongplussubmediant.EquipmentStudioproduces a result with a PCM array.An imported Wiggle performance:
submediant.SongDataplussubmediant.Studio, orsubmediant.replay(), returns verified WAV bytes. Decode that container to obtain PCM.A synthesis graph:
submediant.render_recipe()orsubmediant.render_asset()returns integer sample arrays directly.
All three paths currently use mono audio at 24,000 Hz and signed 16-bit signal values. The returned Python types differ: do not write WAV bytes to a device expecting headerless PCM, or interpret integer samples as normalized floats.
Compose notes and render PCM¶
This complete example builds three pitched-percussion notes, one xylophone,
an explicit output endpoint, and a part-to-device binding. It writes a WAV
and a headerless signed-16-bit little-endian file under build/python-api/.
"""Compose three mallet strikes using only typed public data and built-in profiles."""
from pathlib import Path
from submediant import (
EquipmentStudio, EquipmentStudioDefinition, MusicalPart, MusicalSong,
Note, PartAssignment, PerformanceBinding, XylophoneDefinition,
)
from submediant.component_model import InstrumentFamily
from submediant.equipment_model import Endpoint
def main():
rate = 24_000
notes = tuple(
Note(f"strike-{i}", i * 6_000, 3_000, pitch, 0.6, f"bar-{pitch}")
for i, pitch in enumerate((65, 69, 72))
)
song = MusicalSong(
title="Three mallet strikes",
duration_frames=18_000,
parts=(MusicalPart("melody", InstrumentFamily.PERCUSSION, notes),),
)
definition = EquipmentStudioDefinition(
id="mallet-demo",
devices=(XylophoneDefinition("xylo", "Xylophone", level=0.3),),
connections=(),
master=Endpoint("xylo", "out"),
)
binding = PerformanceBinding((PartAssignment("melody", "xylo"),))
studio = EquipmentStudio(definition)
with studio.session(song, binding).render() as result:
pcm = result.pcm.copy() # Retain an array owned by this application.
wav = result.wav
print(f"{result.frames} frames at {rate} Hz; {pcm.dtype}; mono")
output = Path("build/python-api")
output.mkdir(parents=True, exist_ok=True)
(output / "three-strikes.wav").write_bytes(wav)
(output / "three-strikes.s16le").write_bytes(pcm.tobytes())
return pcm, wav
if __name__ == "__main__":
main()
Run it with:
python docs/sphinx/examples/compose_pcm.py
The score uses integer sample frames: 6,000 frames is 0.25 seconds. pitch
is a MIDI note number and velocity is a dimensionless value in [0, 1].
voice has an instrument-specific meaning; this xylophone requires
bar-65 for MIDI 65 and supports pitches 65–83. It is a percussion-family
instrument even though its notes have pitch. Its natural ringing is deliberate;
continuous bends are unsupported.
The instrument owns its model and synthesis controls. The song owns notes and
timing. The binding explicitly connects the melody part to xylo.
Endpoint and InstrumentFamily use their documented supporting-module
imports; they are not package-root exports.
The returned in-memory result.pcm is a read-only NumPy array with dtype
<i2 and shape (result.frames,). Ringing and effect tails may extend
beyond song.duration_frames. Use the actual returned length. Copy the
array when you want independently owned, writable samples. To obtain
normalized floating-point samples for another library:
normalized = pcm.astype("float32") / 32768.0
An audio device must be configured for the matching rate/channel/sample format, or the application must resample/convert explicitly. Submediant does not open a sound device and these calls do not provide realtime streaming.
Reuse a studio or load descriptors¶
Reuse immutable definitions and the EquipmentStudio facade. Call session
for each song/binding to construct isolated services. The supported JSON
boundary is equivalent to typed construction:
from submediant import (
EquipmentStudio, EquipmentStudioDefinition, MusicalSong, PerformanceBinding,
)
root = "examples/performance/xylophone-trio"
song = MusicalSong.load(f"{root}/song.json")
definition = EquipmentStudioDefinition.load(f"{root}/hardrubber.equipment.json")
binding = PerformanceBinding.load(f"{root}/binding.json")
studio = EquipmentStudio(definition)
session = studio.session(song, binding)
This creates a validated session without rendering audio yet. A descriptor selects supported data models; it never imports arbitrary executable Python classes.
Results, exports, and verification¶
session.render() is the in-memory path. It retains measured device signals
as float64 arrays, distinct from final quantized PCM. Very large observation
sets are rejected rather than allocated without a bound. Use export for
disk-backed rendering:
with studio.session(song, binding).export("build/performance.wav") as result:
print(result.frames, result.render_id, result.wav_sha256)
raw_pcm_bytes = result.pcm.tobytes()
Unlike the in-memory result, an export result’s pcm is a reader, not an
ndarray. tobytes() materializes all samples; wav materializes the whole
WAV. copy_wav(destination) copies the temporary WAV without loading it all
into Python memory. Temporary files and signal readers are invalid after
close or context exit; the published destination WAV remains available.
expected=(render_id, wav_sha256) optionally verifies an equipment render.
The render ID includes the effective configuration, implementation identities,
interpretation, audio format, and NumPy version. A WAV digest hashes the whole
container. Do not carry a pin across a deliberate synthesis change or promise
byte equality across arbitrary package/dependency versions.
An imported SongData instead carries its already approved WAV digest. Normal replay always enforces it; an override declaring compatible capabilities does not disable this check.
Decode verified imported playback to PCM¶
This uses the repository’s distributable compressed fixture and preserves its approved performance. It imports data rather than composing new notes.
"""Replay the distributable imported performance and decode its verified WAV."""
import gzip
import io
from pathlib import Path
import wave
import numpy as np
from submediant import SongData, Studio
def main():
source = Path("tests/fixtures/black-canal.sequence.json.gz")
with gzip.open(source, "rb") as stream:
song = SongData.from_json(stream.read())
session = Studio().session(song)
wav_bytes = session.render_audio() # Includes a WAV header; verifies the approved hash.
with wave.open(io.BytesIO(wav_bytes), "rb") as wav:
assert (wav.getnchannels(), wav.getsampwidth(), wav.getframerate()) == (1, 2, 24_000)
pcm = np.frombuffer(wav.readframes(wav.getnframes()), dtype="<i2").copy()
assert len(pcm) == song.output_frames
print(f"Verified {len(pcm)} mono PCM frames")
return pcm, wav_bytes
if __name__ == "__main__":
main()
Run it with:
python docs/sphinx/examples/replay_pcm.py
replay(song) is a convenience alternative to
Studio().session(song).render_audio(). Both return WAV bytes. Use wave
to read their frames; a fixed header-offset assumption is not part of the API.
For bounded inspection, pass RenderTrace(start_frame=0, stop_frame=2400)
as trace= to either imported-audio entry point. Trace bounds select observed
frames; they do not shorten the rendered WAV or skip its verification.
Render a graph directly¶
This lower-level example produces a 100 ms, 440 Hz sine graph. Recipe duration
uses milliseconds and frequencyMilliHz uses thousandths of a hertz.
"""Render a short graph directly to integer samples and a WAV file."""
from pathlib import Path
import wave
from submediant import render_recipe
def main():
recipe = {
"version": 1,
"engine": "wiggle-vm-v1",
"kind": "sound",
"nodes": [{
"id": "tone", "op": "sine", "inputs": {},
"params": {
"durationMs": 100, "frequencyMilliHz": 440_000,
"amplitudeMilli": 250, "phase": 0,
},
}],
"output": "tone",
}
pcm = render_recipe(recipe) # One-dimensional int32 storage; int16 signal range.
output = Path("build/python-api")
output.mkdir(parents=True, exist_ok=True)
with wave.open(str(output / "tone.wav"), "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(24_000)
wav.writeframes(pcm.astype("<i2").tobytes())
return pcm
if __name__ == "__main__":
main()
Run it with:
python docs/sphinx/examples/recipe_pcm.py
render_recipe returns a one-dimensional int32 array whose signal values
fit signed 16-bit PCM. Convert explicitly to <i2 before writing two-byte
samples. This differs from the equipment result, whose PCM already has that
dtype. Filter recipes additionally require a named input sample array for each
input port; an input’s sample rate must be 24,000 Hz.
render_asset(root_id, assets) performs a complete asset dependency tree from
a serialized bundle. It returns the same integer-sample representation, without
the song’s placements, room mix, or final WAV pin. Asset validation still
applies. Support is bounded by the implemented engine operations and fixtures;
accepting an engine name is not proof of all upstream interoperability.
Extend the intended interfaces¶
Subclass submediant.EquipmentStudioConfig or
submediant.StudioConfig to select trusted service implementations.
Override the existing typed get_*_class or owning option hooks, and call
super().configure() when adding bindings. Pass the Config class as
config_type to the studio; never share a configured instance across songs.
Fresh sessions isolate runtime state, without promising concurrent use of one
session is safe.
Keep executable service bindings in configuration and musical content in MusicalSong/SongData. Definition objects describe instruments and routing; they do not become running DSP services until the session is constructed. The grouped Python API reference documents exports, returned interfaces, and supporting types with their actual import paths.
Validation failures generally raise ValueError. Imported records may also
raise KeyError for missing fields, file loaders can raise OSError or
JSON decode errors, and optional video can raise tool/dependency errors.
Handle these at the application’s boundary; do not suppress a failed hash
check and treat its output as an approved performance.