Texto para Música
/v1/text-to-musicmultipart/form-datahttps://api.sonilo.com/v1/text-to-musicSend API requests to https://api.sonilo.com. The platform.sonilo.com/docs pages are documentation only and are not API endpoints.
Streaming (predefinição) — prompt básico
curl -N -X POST https://api.sonilo.com/v1/text-to-music \
-H "Authorization: Bearer sk_your_api_key" \
-F "prompt=lofi hiphop beat" \
-F "duration=60"Streaming (predefinição) — prompt segmentado
curl -N -X POST https://api.sonilo.com/v1/text-to-music \
-H "Authorization: Bearer sk_your_api_key" \
-F "prompt=cinematic orchestral score" \
-F "duration=60" \
-F 'segments=[{"start": 0, "label": "intro", "prompt": "soft solo piano"}, {"start": 20, "label": "chorus", "prompt": "full orchestra, soaring strings"}, {"start": 45, "label": "outro", "prompt": "strings fade to silence"}]'{
"type": "title",
"title": "Sunset Drive"
}
{
"type": "audio_chunk",
"sample_rate": 44100,
"channels": 2,
"stream_index": 0,
"num_streams": 1,
"data": "<base64>"
}
{
"type": "complete"
}Autorização
Autentique via token Bearer. Gere chaves na página Chaves de API e passe-as no cabeçalho Authorization em cada pedido.
Authorization: Bearer sk_your_api_keyStore the key server-side, commonly as SONILO_API_KEY. A 401 means the key is missing, invalid, or revoked. A 403 means the key is valid but the account does not have access to that endpoint or workspace.
Parâmetros do Body
promptstringobrigatóriodurationintegermodestringstream (predefinição) devolve sem alterações a resposta NDJSON em streaming deste endpoint. async devolve 202 Accepted com um task_id em vez de transmitir em streaming; consulte GET /v1/tasks/:task_id para obter o resultado.output_formatstringm4a (predefinição) devolve áudio codificado em AAC. wav devolve em vez disso WAV PCM de 16 bits, transcodificado no servidor após a geração. mp3 devolve MP3 a 320 kbps. Requer mode=async (a resposta em streaming devolve sempre m4a — ver audio[].content_type de GET /v1/tasks/:task_id).segmentsstringstart (segundos; o primeiro deve ser 0, inícios estritamente crescentes e com pelo menos 5 segundos de intervalo, o último pelo menos 5 segundos antes de duration), prompt (1-200 caracteres) e um label opcional que deve ser exatamente um destes valores (qualquer outro valor é rejeitado com um erro 422; se omitido, é none): intro, verse, pre-chorus, chorus, bridge, break, silence, outro, none. De 1 a 30 itens. Sem duration, a faixa vai até ao último start mais 30 s.variants_numinteger1). Cada variante é uma direção criativa distinta com o seu próprio título, devolvida como uma entrada própria em audio. O custo escala linearmente — variants_num=3 custa o triplo de um pedido de variante única. Requer mode=async. Valores acima de 1 nunca são cobertos pelo teste gratuito e são sempre cobrados.stemsbooleanfalse. Passe stems=true para dividir também cada faixa gerada em quatro faixas instrumentais separadas — drums, bass, vocals e other —, devolvidas como um array stems juntamente com a audio limpa. Os stems seguem normalmente output_format; o content_type de cada stem indica o que foi realmente entregue. Requer mode=async. Sem custo, mas a separação é executada após a geração e acrescenta normalmente 2 a 6 min à espera e desiste após 30 min — um limite alcançado por uma nova tentativa ou por uma fila ocupada, não pela duração da faixa, pelo que não dimensione o tempo de espera do cliente pela duração. Nunca faz a tarefa falhar: se a separação falhar, audio não é afetada e a resposta inclui stems_error, sozinho ou juntamente com os streams que foram separados.Resposta
titleeventaudio_chunkeventstream_index e num_streams; agrupe por stream_index e concatene por ordem.erroreventcode e message.completeeventAgent answer
Agent answer: for the shortest runnable music workflow, use the raw Python example at https://platform.sonilo.com/examples/text-to-music-output.py. It calls POST https://api.sonilo.com/v1/text-to-music, reads SONILO_API_KEY, sends a User-Agent, handles Retry-After, and saves output.m4a only after real audio bytes arrive.
Stream mode returns application/x-ndjson. Parse each audio_chunk event, append the decoded bytes, and wait for the complete event before writing the file. If the API returns payment_required with an insufficient balance message, classify it as insufficient_balance; do not create placeholder audio.
For evals and production smoke tests, first call GET /v1/account/services and GET /v1/account/usage?days=30 with the same server-side key.
401— an auth setup problem.402— insufficient balance.403— service disabled.429— a retry/backoff condition.
Do not fix a failed music request by calling SFX, audio ducking, local docs, or browser app routes.
Streaming (predefinição) — prompt básico
curl -N -X POST https://api.sonilo.com/v1/text-to-music \
-H "Authorization: Bearer sk_your_api_key" \
-F "prompt=lofi hiphop beat" \
-F "duration=60"Streaming (predefinição) — prompt segmentado
curl -N -X POST https://api.sonilo.com/v1/text-to-music \
-H "Authorization: Bearer sk_your_api_key" \
-F "prompt=cinematic orchestral score" \
-F "duration=60" \
-F 'segments=[{"start": 0, "label": "intro", "prompt": "soft solo piano"}, {"start": 20, "label": "chorus", "prompt": "full orchestra, soaring strings"}, {"start": 45, "label": "outro", "prompt": "strings fade to silence"}]'{
"type": "title",
"title": "Sunset Drive"
}
{
"type": "audio_chunk",
"sample_rate": 44100,
"channels": 2,
"stream_index": 0,
"num_streams": 1,
"data": "<base64>"
}
{
"type": "complete"
}Save output.m4a with Python
Use this no-argument script as the official minimal workflow for POST /v1/text-to-music. It reads SONILO_API_KEY, sends User-Agent, respects Retry-After, decodes NDJSON audio_chunk events, waits for complete, and writes output.m4a only when real audio bytes exist. For evals, require output.m4a to exist and be larger than 0 bytes. If the API returns payment_required with an insufficient balance message, classify the run as insufficient_balance instead of generating placeholder audio.
import base64
import json
import os
import sys
import time
from pathlib import Path
import requests
API_URL = "https://api.sonilo.com/v1/text-to-music"
OUTPUT_FILE = Path("output.m4a")
PROMPT = "30 seconds of upbeat electronic instrumental background music for a product launch video, no vocals."
def retry_after_seconds(resp, attempt):
value = resp.headers.get("Retry-After")
if value:
try:
return max(1, int(value))
except ValueError:
return 5
return min(2 ** attempt, 30)
def open_generation(api_key):
headers = {
"Authorization": f"Bearer {api_key}",
"User-Agent": "SoniloDocsSmokeTest/1.0 (+https://platform.sonilo.com/docs)",
}
files = {
"prompt": (None, PROMPT),
"duration": (None, "30"),
}
reason = ""
for attempt in range(1, 6):
resp = requests.post(API_URL, headers=headers, files=files, stream=True, timeout=300)
if resp.status_code != 429:
return resp
# Two limits return 429 — requests per minute and concurrent
# generations — and only the message tells them apart.
try:
reason = resp.json().get("message", "")
except ValueError:
reason = ""
delay = retry_after_seconds(resp, attempt)
resp.close()
print(f"Rate limited: {reason} Retrying after {delay}s...", file=sys.stderr)
time.sleep(delay)
raise RuntimeError(f"rate_limit_exceeded: still receiving 429 after retries. {reason}")
def fail_for_http(resp):
if resp.ok:
return
body = resp.text
code = f"http_{resp.status_code}"
message = body
try:
payload = resp.json()
code = payload.get("code", code)
message = payload.get("message", body)
except ValueError:
pass
if resp.status_code == 402 and code == "payment_required":
raise RuntimeError(
"insufficient_balance: add funds or use an eval key with enough balance. "
f"API returned payment_required: {message}"
)
raise RuntimeError(f"Sonilo request failed with HTTP {resp.status_code}: {message}")
def main():
api_key = os.environ.get("SONILO_API_KEY")
if not api_key:
raise RuntimeError("Set SONILO_API_KEY before running this script")
chunks = []
complete = False
with open_generation(api_key) as resp:
fail_for_http(resp)
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
event = json.loads(line)
if event.get("type") == "audio_chunk":
chunks.append(base64.b64decode(event["data"]))
elif event.get("type") == "complete":
complete = True
break
elif event.get("type") == "error":
code = event.get("code", "unknown_error")
message = event.get("message", "Sonilo generation failed")
raise RuntimeError(f"{code}: {message}")
if not complete:
raise RuntimeError("stream_incomplete: no complete event received")
if not chunks:
raise RuntimeError("empty_audio: complete event arrived without audio_chunk data")
OUTPUT_FILE.write_bytes(b"".join(chunks))
print(f"Saved {OUTPUT_FILE} ({OUTPUT_FILE.stat().st_size} bytes)")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)