Skip to content

Python プロジェクト API ​

Project はヘッドレス DAW のアレンジモデルで、トラック、クリップ、テンポ、マーカー、取り消しを持ち、オフラインでレンダーします。ボーカル編集セッションのクラスは、単音のテイクをオフラインで編集します。このページには、タスクの対応表、ライフサイクルの規則、シグネチャを載せています。作業手順は下記のガイドを参照してください。インストゥルメントによるレンダーは インストゥルメントとライブ MIDI、ライブ再生は リアルタイムエンジン にあります。

タスク別の参照先 ​

やりたいことAPIガイド
トラック、クリップ、テンポ、マーカー、undo/redo を編集するProject(コンテキストマネージャ。with を使う)プロジェクト編集
プロジェクトで解決できなかったオーディオソースを列挙するProject.unresolved_audio_sources()プロジェクト編集
python
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)
    # ... クリップと MIDI イベントを追加します(プロジェクト編集ガイドを参照) ...
    audio = project.bounce(
        synth_instruments=[
            sonare.ProjectInstrumentBinding(
                destination_id=0,
                instrument=sonare.SynthPatch(preset="ePiano"),
            )
        ],
        num_channels=2,
    )

Project.auto_tempo(audio, sample_rate, ...) は ProjectAutoTempoResult(bpm、bpm_confidence、検出した time_signature)を返します。apply_time_signatures=False でも拍子は返ります。auto_tempo と analyze_tempo はどちらも sample_rate より後の引数がすべてキーワード専用です。set_mixer_scene(scene) にはデコード済みシーンのマッピングを渡し、クリアする場合は None を渡します。未設定時の mixer_scene() は None を返します。tracks()、clips()、sources()、tempo_segments()、time_signatures() は保存済みの一覧を返します。テンポと拍子の一覧が空なら、そのまま空で、実効値が自動で追加されることはありません。

ライフサイクル ​

作成 ​

sonare.Project() は空のアレンジを作り、Project.from_json(json) は保存済みのアレンジを読み込みます。VocalEditSession(samples, sample_rate) はモノラルの音声を解析してセッションを開きます。session.begin_edit() が VocalEditDraft を開き、確定したリビジョンは VocalRenderSnapshot か VocalRenderJob でレンダーします。ボーカル編集は capabilities().features.vocal_edit と vocal_edit_abi_version() で有無を確認してください。

使用 ​

これらはオフラインのコントロールスレッド用オブジェクトで、リアルタイム安全ではなく、オーディオコールバックの中では動かしません。Project の編集は取り消せます。bounce() とボーカルのレンダーは呼び出し側のスレッドで同期的に実行されます。プロジェクトをライブで再生するには、コンパイルして停止中の RealtimeEngine にタイムラインを適用します。

解放 ​

Project、VocalEditSession、VocalEditDraft、VocalRenderSnapshot、VocalRenderJob はいずれも冪等な close() を持ち、コンテキストマネージャとして使えるので、with なら例外時にも解放されます(ネイティブハンドルの解放)。close() の後に呼び出すと INVALID_STATE の SonareError が上がります。Project.close() がネイティブ呼び出しの実行中に届いた場合、クローズはその呼び出しの終了まで遅延し、クローズ待ちの間の呼び出しも INVALID_STATE になります。ProjectTimeline も同じ流儀で、ガベージコレクトされるオブジェクトは自分自身を閉じます。

エラー ​

引数の拒否は SonareValueError です。解釈できないプロジェクトドキュメントは、INVALID_FORMAT を持つ素の SonareError です。閉じたオブジェクトの呼び出しや、導出した長さが収まらないバウンスは INVALID_STATE です。表全体は エラー契約、例外クラスは Python 型定義 にあります。

不透明なアシストサイドカー ​

Project は、プロジェクトごとでアンドゥ可能、モジュールが所有する不透明なバイト列(アシストサイドカー)を保持できます。スコープはモジュール ID・ターゲットトラック・領域です。project.set_assist_sidecar(module_id, payload, *, schema_version=0, target_track_id=0, region_start_ppq=0.0, region_end_ppq=0.0) で設定し、project.assist_sidecars()(AssistSidecar のリスト)で読み出します。バインディング間の詳細は プロジェクト編集 を参照してください。

Project ​

次のブロックは、パッケージが宣言する Project の公開メンバーを列挙したものです。各呼び出しを作業の流れの中で確認するには プロジェクト編集 を参照してください。トラック、クリップ、MIDI のメンバーは Python プロジェクト編集 API と Python プロジェクト MIDI API、それらが返すレコード型は Python 型定義 にあります。

作成、解放、シリアライズ ​

ProjectTimeline は、コンパイルしたプロジェクトのタイムラインを受け取るハンドルです。Project と同じく close() を持ち、コンテキストマネージャとして使えます。

python
# 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_kind_names() は、プロジェクトのオートメーションレーンで使うターゲット種別トークンを C ABI の ordinal 順に返します。

python
from libsonare import automation_target_kind_names

target_kinds = automation_target_kind_names()
assert target_kinds[0] == "opaque"
python
# Return the automation target kind tokens in C ABI ordinal order.
def automation_target_kind_names() -> list[ProjectAutomationTargetKind]: ...

状態の参照 ​

python
# 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: TimeSignature

レンダーとサウンドフォント ​

Project.bounce() は ProjectBounceResult を返します。channels は (num_channels, frames) 形状のプレーナー float32 配列で、sample_rate はプロジェクトのレートです。バウンスに sample_rate 引数はありません。builtin_instruments、synth_instruments、instruments には ProjectInstrumentBinding(instrument=..., destination_id=0)、sf2_instruments には ProjectSf2InstrumentBinding(instrument=..., destination_id=0, sound_font_uri=...)、controller_profiles には ProjectControllerProfileBinding(destination_id=..., preset_name=...)、articulations には ProjectArticulationBinding(destination_id=..., channel=..., articulation=...) のレコードを使います。4 種類のバインディングレコードはすべてキーワード専用です。count_in_frames(count_in_bars) はプロジェクトの初期テンポと拍子におけるプリロールのフレーム数を返します。SoundFont の読み込み、クリア、件数、マニフェストの各メソッドは任意のキーワード専用 uri を受け取り、省略すると既定フォントを選びます。

python
# 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: Articulation

ボーカル編集セッション ​

セッションは解析済みのノート、確定したリビジョン、取り消し履歴を保持し、ドラフトは確定リビジョンに対する 1 回の編集トランザクションです。流れは オフライン・ボーカル編集 で説明しています。

python
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: ...

ボーカル編集をプロジェクトに適用する ​

python
@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']