Python Projects API
Project is the headless-DAW arrangement model: tracks, clips, tempo, markers and undo, rendered offline. The vocal-edit session classes edit a monophonic take offline. This page holds the task map, the lifecycle rules and the signatures; the guides linked below teach the workflows. Rendering through instruments is on Instruments and Live MIDI, and live playback on Realtime Engine.
Where each task lives
| Task | API | Guide |
|---|---|---|
| Author tracks, clips, tempo, markers, undo/redo | Project (a context manager — use with) | Project Editing |
| List audio sources a project could not resolve | Project.unresolved_audio_sources() | Project Editing |
import libsonare as sonare
with sonare.Project() as project:
project.set_sample_rate(48000)
track = project.add_track(kind="midi")
project.set_track_midi_destination(track, 0)
# ... add clips and MIDI events (see the Project Editing guide) ...
audio = project.bounce(
synth_instruments=[
sonare.ProjectInstrumentBinding(
destination_id=0,
instrument=sonare.SynthPatch(preset="ePiano"),
)
],
num_channels=2,
)Project.auto_tempo(audio, sample_rate, ...) returns ProjectAutoTempoResult (bpm, bpm_confidence, and the detected time_signature), even when apply_time_signatures=False. In both auto_tempo and analyze_tempo, every argument after sample_rate is keyword-only. set_mixer_scene(scene) takes a decoded scene mapping; pass None to clear it, and mixer_scene() returns None when unset. tracks(), clips(), sources(), tempo_segments(), and time_signatures() return stored lists; empty tempo and meter maps remain empty and do not materialize effective defaults.
Lifecycle
Create
sonare.Project() starts an empty arrangement and Project.from_json(json) loads a saved one. VocalEditSession(samples, sample_rate) analyses mono audio and opens a session; session.begin_edit() opens a VocalEditDraft, and a committed revision is rendered through a VocalRenderSnapshot or a VocalRenderJob. Gate vocal editing on capabilities().features.vocal_edit and vocal_edit_abi_version().
Use
These are offline, control-thread objects: none is realtime-safe and none runs on an audio callback. Project edits are undoable; bounce() and the vocal renders run synchronously on the calling thread. To play a project live, compile it and apply the timeline to a stopped RealtimeEngine.
Release
Project, VocalEditSession, VocalEditDraft, VocalRenderSnapshot and VocalRenderJob each have an idempotent close() and work as context managers, so with releases them on an exception too (Releasing Native Handles). A call after close() raises SonareError with INVALID_STATE. A Project.close() that arrives while a native call is active is deferred to the end of that call, and a call made while the close is pending raises INVALID_STATE too. ProjectTimeline follows the same pattern, and an object that is garbage collected closes itself.
Errors
A refused argument is SonareValueError; a project document that does not parse is a plain SonareError with INVALID_FORMAT; a closed object, or a bounce whose derived length does not fit, is INVALID_STATE. The full table is Error Contract, and the classes are on Python Types.
Opaque assist sidecars
Project can carry per-project, undoable, module-owned opaque byte blobs (assist sidecars), scoped by module ID, target track, and a region. Set one with project.set_assist_sidecar(module_id, payload, *, schema_version=0, target_track_id=0, region_start_ppq=0.0, region_end_ppq=0.0); read them back with project.assist_sidecars(), a list of AssistSidecar. See Project Editing for the cross-binding details.
Project
The blocks below list the public members of Project as the package declares them; Project Editing shows each call in a workflow. The track, clip and MIDI members are on Python Project Edit API and Python Project MIDI API, and the record types they return on Python Types.
Create, release and serialize
ProjectTimeline is the handle a compiled project's timeline comes in; like Project it has close() and works as a context manager.
# Immutable compiled playback snapshot of a :class:`Project`.
class ProjectTimeline:
def __init__(self, handle: ctypes.c_void_p) -> None: ...
# Release the native timeline handle (idempotent).
def close(self) -> None: ...
# Return the object itself for ``with`` use.
def __enter__(self) -> ProjectTimeline: ...
# Close the object on leaving the ``with`` block; never suppresses exceptions.
def __exit__(self, *_exc: object) -> None: ...
def __init__(self) -> None: ...
# Create a new empty project.
@classmethod
def create(cls) -> Self: ...
# Destroy the native project; deferred to the end of an active native call.
def close(self) -> None: ...
# Return the object itself for ``with`` use.
def __enter__(self) -> Project: ...
# Close the object on leaving the ``with`` block; never suppresses exceptions.
def __exit__(self, *_exc: object) -> None: ...
# Compile the project into an RT-readable timeline.
def compile(self, *, with_timeline: bool = False) -> ProjectCompileResult: ...
# Serialize the project to deterministic JSON as raw UTF-8 bytes.
def to_json_bytes(self) -> bytes: ...
# Serialize the project to deterministic JSON (UTF-8 decoded).
def to_json(self) -> str: ...
# Deserialize project JSON into a new :class:`Project`.
@classmethod
def from_json(cls, document: str | bytes) -> Project: ...
# Deserialize project JSON and return warnings from successful loads.
@classmethod
def from_json_with_diagnostics(cls, document: str | bytes) -> ProjectDeserializeResult: ...
# Commit a full-source vocal render to one clip or take.
def apply_vocal_edit(
self,
*,
clip_id: int,
expected_source_id: int,
expected_source_sample_rate: int,
expected_source_sample_count: int,
expected_source_sha256: str,
expected_clip_length_ppq: float,
expected_source_offset_ppq: float,
rendered_mono: Sequence[float] | np.ndarray[Any, Any],
rendered_sample_rate: int,
render_token: VocalStateToken,
sve1: bytes | bytearray | memoryview,
take_id: int | None = None,
rendered_start_sample: int = 0,
) -> ProjectVocalEditApplyResult: ...
# Return the sources the project's vocal edits depend on.
def vocal_edit_dependencies(self) -> tuple[ProjectVocalEditDependency, ...]: ...
# Rehydrate the project's vocal edits from the given original sources.
def rehydrate_vocal_edits(
self,
originals: Sequence[ProjectVocalOriginalSource],
*,
cancel: Callable[[], bool] | None = None,
) -> tuple[ProjectVocalRehydrateItem, ...]: ...Automation target kinds
automation_target_kind_names() returns the target-kind tokens in the C ABI ordinal order used by project automation lanes.
from libsonare import automation_target_kind_names
target_kinds = automation_target_kind_names()
assert target_kinds[0] == "opaque"# Return the automation target kind tokens in C ABI ordinal order.
def automation_target_kind_names() -> list[ProjectAutomationTargetKind]: ...State and read-back
# Return ranked primary/half/double tempo and meter candidates without editing.
def analyze_tempo(
self,
audio: Sequence[float] | np.ndarray,
sample_rate: int,
*,
adaptive_tempo: bool | None = None,
tempo_update_interval_beats: int | None = None,
ramp_threshold: float | None = None,
include_octave_candidates: bool | None = None,
) -> list[dict[str, object]]: ...
# Detect tempo from a mono buffer and install it (undoable).
def auto_tempo(
self,
audio: Sequence[float] | np.ndarray,
sample_rate: int,
*,
candidate_index: int = 0,
apply_time_signatures: bool = False,
adaptive_tempo: bool | None = None,
tempo_update_interval_beats: int | None = None,
ramp_threshold: float | None = None,
include_octave_candidates: bool | None = None,
) -> ProjectAutoTempoResult: ...
# Snap a PPQ coordinate to a project-grid line.
def snap_to_grid(self, ppq: float, strength: float = 1.0, division: int = 1) -> float: ...
# Replace the project's key annotation stream via an undoable command.
def annotate_keys(self, keys: Sequence[Mapping[str, object]]) -> None: ...
# Replace the project's chord-symbol annotation stream (undoable command).
def annotate_chords(self, chords: Sequence[Mapping[str, object]]) -> None: ...
# Add or update an opaque assist sidecar (undoable command).
def set_assist_sidecar(
self,
module_id: str,
payload: bytes = b'',
*,
schema_version: int = 0,
target_track_id: int = 0,
region_start_ppq: float = 0.0,
region_end_ppq: float = 0.0,
) -> None: ...
# Return all stored assist sidecars as a list of :class:`AssistSidecar`.
def assist_sidecars(self) -> list[AssistSidecar]: ...
# The project sample rate in Hz.
@property
def sample_rate(self) -> float: ...
# The project's clip-overlap policy.
@property
def overlap_policy(self) -> ProjectOverlapPolicy: ...
# Set the project's clip-overlap policy.
def set_overlap_policy(self, policy: ProjectOverlapPolicy) -> None: ...
# Add or replace a marker; return its id.
def set_marker(
self,
ppq: float,
*,
marker_id: int | None = None,
name: str | None = None,
kind: MarkerKind | None = None,
key_fifths: int | None = None,
key_minor: bool | None = None,
) -> int: ...
# Replace the project's mixer scene, or clear it when ``scene`` is ``None``.
def set_mixer_scene(self, scene: MixSceneDocument | None) -> None: ...
# Read the project's mixer scene, or return ``None`` when it is unset.
def mixer_scene(self) -> MixSceneDocument | None: ...
# Replace the project's tempo map.
def set_tempo_segments(self, segments: Sequence[Mapping[str, float]]) -> None: ...
# Replace the project's time-signature map.
def set_time_signatures(self, segments: Sequence[Mapping[str, float]]) -> None: ...
# Every marker, in stored order, including its kind and key.
def markers(self) -> list[ProjectMarker]: ...
# Every track, in stored order.
def tracks(self) -> list[ProjectTrack]: ...
# Every clip, in stored order.
def clips(self) -> list[ProjectClip]: ...
# Every registered source, in stored order.
def sources(self) -> list[ProjectSource]: ...
# Every tempo-map segment in stored order, as :meth:`set_tempo_segments` takes it.
def tempo_segments(self) -> list[dict[str, float]]: ...
# Every time-signature segment in stored order, as :meth:`set_time_signatures` takes it.
def time_signatures(self) -> list[dict[str, float | int]]: ...
# Return the compile result captured by the last successful bounce.
def last_bounce_compile_result(self) -> ProjectCompileResult | None: ...
# The selected tempo and detected meter from :meth:`Project.auto_tempo`.
@dataclass(frozen=True, slots=True)
class ProjectAutoTempoResult:
bpm: float
bpm_confidence: float
time_signature: TimeSignatureRendering and SoundFonts
Project.bounce() returns ProjectBounceResult; channels is a planar float32 array shaped (num_channels, frames), and sample_rate is the project's rate. There is no bounce sample_rate argument. builtin_instruments, synth_instruments, and instruments use ProjectInstrumentBinding(instrument=..., destination_id=0) records; sf2_instruments uses ProjectSf2InstrumentBinding(instrument=..., destination_id=0, sound_font_uri=...); controller_profiles uses ProjectControllerProfileBinding(destination_id=..., preset_name=...); and articulations uses ProjectArticulationBinding(destination_id=..., channel=..., articulation=...). All four binding record types are keyword-only. count_in_frames(count_in_bars) reports the pre-roll frame count at the project's initial tempo and meter. SoundFont load, clear, count, and manifest methods take optional keyword-only uri; omitting it selects the default font.
# Return the pre-roll length at the project's initial tempo and meter.
def count_in_frames(self, count_in_bars: int) -> int: ...
# Compile and render the project offline to planar float audio.
def bounce(
self,
*,
instruments: Sequence[ProjectInstrumentBinding[ExternalInstrument]] | None = None,
builtin_instruments: Sequence[ProjectInstrumentBinding[BuiltinSynthConfig]] | None = None,
synth_instruments: Sequence[ProjectInstrumentBinding[SynthPatch]] | None = None,
sf2_instruments: Sequence[ProjectSf2InstrumentBinding] | None = None,
total_frames: int | None = None,
block_size: int | None = None,
num_channels: int | None = None,
instrument_latency_samples: int | None = 0,
metronome: EngineMetronomeConfig | None = None,
count_in_bars: int = 0,
controller_profiles: Sequence[ProjectControllerProfileBinding] | None = None,
articulations: Sequence[ProjectArticulationBinding] | None = None,
) -> ProjectBounceResult: ...
# Load (parse) SoundFont 2 bytes into the project.
def load_sound_font(
self,
data: bytes | bytearray | memoryview,
*,
uri: str | None = None,
) -> None: ...
# Release the SoundFont at ``uri``, or the default one when omitted.
def clear_sound_font(self, *, uri: str | None = None) -> None: ...
# Return the preset count at ``uri``, or in the default SoundFont.
def sound_font_preset_count(self, *, uri: str | None = None) -> int: ...
# Enumerate the programs the arrangement plays and their backends.
def sound_font_manifest(self, *, uri: str | None = None) -> list[Sf2ProgramStatus]: ...
# Rendered planar project audio and its sample rate.
@dataclass(frozen=True, slots=True)
class ProjectBounceResult:
channels: np.ndarray
sample_rate: int
# An instrument supplied for one project bounce.
@dataclass(frozen=True, slots=True, kw_only=True)
class ProjectInstrumentBinding(Generic[_InstrumentConfig]):
instrument: _InstrumentConfig
destination_id: int | None = None
# A SoundFont instrument supplied for one project bounce.
@dataclass(frozen=True, slots=True, kw_only=True)
class ProjectSf2InstrumentBinding(ProjectInstrumentBinding[Sf2InstrumentConfig]):
sound_font_uri: str | None = None
instrument: _InstrumentConfig
destination_id: int | None = None
# A controller profile selected for one instrument in a project bounce.
@dataclass(frozen=True, slots=True, kw_only=True)
class ProjectControllerProfileBinding:
destination_id: int
preset_name: str
# A note articulation selected for one destination and channel in a project bounce.
@dataclass(frozen=True, slots=True, kw_only=True)
class ProjectArticulationBinding:
destination_id: int
channel: int
articulation: ArticulationVocal edit sessions
A session holds the analysed notes, a committed revision and the undo history; a draft is one edit transaction against the committed revision. Offline Vocal Editing walks through the flow.
class VocalEditSession:
def __init__(
self,
samples: Sequence[float] | NDArray[Any],
sample_rate: int,
*,
analysis: VocalAnalysis | None = ...,
output_length_samples: int | None = ...,
edge_fade_ms: float | None = ...,
vibrato_cutoff_hz: float | None = ...,
segmentation_threshold_cents: float | None = ...,
min_note_ms: float | None = ...,
frame_length_samples: int | None = ...,
hop_length_samples: int | None = ...,
fmin_hz: float | None = ...,
fmax_hz: float | None = ...,
yin_threshold: float | None = ...,
voiced_threshold: float | None = ...,
centered: bool | None = ...,
reference_hz: float | None = ...,
max_history_bytes: int | None = ...,
max_cache_bytes: int | None = ...,
max_undo_depth: int | None = ...,
max_render_jobs: int | None = ...,
) -> None: ...
@classmethod
def restore(
cls,
samples: Sequence[float] | NDArray[Any],
sample_rate: int,
state: bytes | bytearray | memoryview,
*,
max_history_bytes: int | None = ...,
max_cache_bytes: int | None = ...,
max_undo_depth: int | None = ...,
max_render_jobs: int | None = ...,
) -> VocalEditSession: ...
def __enter__(self) -> Self: ...
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Release the native session; safe to call twice.
def close(self) -> None: ...
# Notes and transitions of the committed state; SonareError (InvalidState) once closed.
def notes(self) -> VocalNotesResult: ...
# The pitch analysis the session was built from.
def analysis(self) -> VocalAnalysisResult: ...
# What the loaded engine supports.
def capabilities(self) -> VocalCapabilities: ...
# State token of the committed state.
def token(self) -> VocalStateToken: ...
# Counter of committed edits.
@property
def revision(self) -> int: ...
# Length of the output in samples.
@property
def output_length_samples(self) -> int: ...
# Whether an undo or a redo is available.
def history(self) -> VocalHistory: ...
# True when an edit can be undone.
@property
def can_undo(self) -> bool: ...
# True when an undone edit can be redone.
@property
def can_redo(self) -> bool: ...
# Open a draft; ``expected_revision`` None means the current revision.
def begin_edit(self, expected_revision: int | None = ...) -> VocalEditDraft: ...
# Undo the last committed edit; ``expected_revision`` None means the current revision.
def undo(self, expected_revision: int | None = ...) -> VocalEditResult: ...
# Redo the last undone edit; ``expected_revision`` None means the current revision.
def redo(self, expected_revision: int | None = ...) -> VocalEditResult: ...
# Measured, target and effective pitch per frame of one note.
def evaluate_pitch(self, note_id: int) -> VocalPitchResult: ...
# Map a source position of a note to the output, in samples.
def source_sample_to_destination_sample(self, note_id: int, source_sample: float) -> float: ...
# Map an output position of a note back to the source, in samples.
def destination_sample_to_source_sample(
self,
note_id: int,
destination_sample: float,
) -> float: ...
# Capture the committed state for rendering.
def capture_render_snapshot(self) -> VocalRenderSnapshot: ...
# Serialise the session state to bytes that ``restore`` accepts.
def export_state(self) -> bytes: ...
def render(
self,
range: VocalRange | Sequence[int | None] | None = ...,
*,
start_sec: float | None = ...,
end_sec: float | None = ...,
request_id: int = ...,
cancel: Callable[[], bool] | None = ...,
) -> VocalRenderResult: ...
class VocalEditDraft:
def __init__(self, session: VocalEditSession, handle: ctypes.c_void_p) -> None: ...
def __enter__(self) -> Self: ...
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Release the native draft; safe to call twice.
def close(self) -> None: ...
# Notes and transitions of the draft; SonareError (InvalidState) once closed.
def notes(self) -> VocalNotesResult: ...
# State token of the draft.
def token(self) -> VocalStateToken: ...
# Apply operations in order; ``expected_generation`` must be the draft's generation.
def apply(
self,
operations: Iterable[VocalOperation],
expected_generation: int,
) -> VocalEditResult: ...
# Commit the draft; ``expected_revision`` None means the session's current revision.
def commit(self, expected_revision: int | None = ...) -> VocalEditResult: ...
# Discard the draft.
def cancel(self) -> None: ...
# Measured, target and effective pitch per frame of one note in the draft.
def evaluate_pitch(self, note_id: int) -> VocalPitchResult: ...
# Map a note's source position in the draft to the output, in samples.
def source_sample_to_destination_sample(self, note_id: int, source_sample: float) -> float: ...
# Map a note's output position in the draft to the source, in samples.
def destination_sample_to_source_sample(
self,
note_id: int,
destination_sample: float,
) -> float: ...
# Capture the draft state for rendering.
def capture_render_snapshot(self) -> VocalRenderSnapshot: ...
class VocalRenderSnapshot:
def __init__(self, handle: ctypes.c_void_p, sample_rate: int) -> None: ...
def __enter__(self) -> Self: ...
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Release the native snapshot; safe to call twice.
def close(self) -> None: ...
# Length of the output in samples.
@property
def output_length_samples(self) -> int: ...
def render(
self,
range: VocalRange | Sequence[int | None] | None = ...,
*,
start_sec: float | None = ...,
end_sec: float | None = ...,
request_id: int = ...,
cancel: Callable[[], bool] | None = ...,
) -> VocalRenderResult: ...
# Start an incremental render of a destination range, in samples or seconds.
def begin_render_job(
self,
range: VocalRange | Sequence[int | None] | None = ...,
*,
start_sec: float | None = ...,
end_sec: float | None = ...,
request_id: int = ...,
) -> VocalRenderJob: ...
class VocalRenderJob:
def __init__(self, snapshot: VocalRenderSnapshot, handle: ctypes.c_void_p) -> None: ...
def __enter__(self) -> Self: ...
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...
# Release the native job; safe to call twice.
def close(self) -> None: ...
# Abandon the render.
def abort(self) -> None: ...
# Run one step; True once the render is complete; ``cancel`` is polled.
def next(self, cancel: Callable[[], bool] | None = ...) -> bool: ...
# Return the rendered result and release the job; ``cancel`` is polled.
def finalize(self, cancel: Callable[[], bool] | None = ...) -> VocalRenderResult: ...
def vocal_edit_abi_version() -> int | None: ...Applying a vocal edit to a project
@dataclass(frozen=True, slots=True)
class ProjectVocalOriginalSource:
source_id: int
mono: Sequence[float] | NDArray[Any]
sample_rate: int
@dataclass(frozen=True, slots=True)
class ProjectVocalEditApplyResult:
clip_id: int
take_id: int | None
original_source_id: int
derived_source_id: int
committed_revision: int
profile_id: int
derived_source_sha256: bytes
sidecar_key: str
@dataclass(frozen=True, slots=True)
class ProjectVocalEditDependency:
clip_id: int
take_id: int | None
original_source_id: int
derived_source_id: int
source_sample_rate: int
profile_id: int
source_sample_count: int
committed_revision: int
original_source_sha256: bytes
derived_source_sha256: bytes
original_pcm_available: bool
derived_pcm_available: bool
reason: VocalReason
sidecar_key: str
@dataclass(frozen=True, slots=True)
class ProjectVocalRehydrateItem:
clip_id: int
take_id: int | None
derived_source_id: int
status: ProjectVocalRehydrateStatus
reason: VocalReason
ProjectVocalRehydrateStatus: TypeAlias = Literal['rehydrated', 'alreadyReady', 'unresolved']