API documentation
These guides show how to do each task with the Treblo API. The API reference lists every endpoint and parameter.
https://api.treblo.com/v1Quick start
Send a prompt and get back a song. The whole song takes a minute or two, but you can start listening in under 20 seconds.
- Create an API key and start your free trial, which gives you 3,000 credits.
- Start a generation with a
promptand the API will provide atask_idimmediately. - Check the task's status until it is
SUCCESS, then fetch the song's URL.
import timeimport requestsAPI = "https://api.treblo.com/v1"headers = {"Authorization": "Bearer your_api_key_here"}# 1. Start the generationresponse = requests.post(f"{API}/generations/v3",headers=headers,json={"prompt": "a chill lofi beat for studying",},)response.raise_for_status()task_id = response.json()["task_id"]# 2. Wait for it to finish, for up to 5 minutesdeadline = time.time() + 300while True:response = requests.get(f"{API}/generations/status/{task_id}", headers=headers)response.raise_for_status()status = response.json()print(status)if status in ("SUCCESS", "FAILURE"):breakif time.time() > deadline:raise SystemExit("Timed out waiting for the song")time.sleep(5)# 3. Get the songsong = requests.get(f"{API}/generations/{task_id}", headers=headers).json()if status == "FAILURE":raise SystemExit(song["error_message"])print(song["song_paths"][0])
Listen before the song is finished
Add "enable_streaming": true to the request. When the status reaches GENERATING_STREAMING_READY, play the song from the streaming URL while we generate the rest. See Stream while generating.
<!-- Works once the task reaches GENERATING_STREAMING_READY --><audio controls autoplay><source src="https://api-stream.treblo.com/stream/your_task_id" type="audio/ogg" /></audio>
Every generation request on this page returns a task_id that you poll in the same way, so the examples below show only the request.
API keys and credits
Send your API key in the Authorization header of every request:
Authorization: Bearer your_api_key_here
Each song costs 100 credits, whatever options you set, so a request for two songs costs 200. We charge only for songs that succeed. GET /credits/balance returns your balance. If you have no credits, the API rejects the request with a 402.
Generate a song
Send a prompt. We write the lyrics, pick the style, and generate the song.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "An upbeat indie rock song about a road trip with old friends",},)print(response.json()) # {"task_id": "..."}
Start with only a prompt
Instrumentals
Set instrumental to true for a song with no vocals. We then use the prompt only to pick the style.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A chill lofi beat for studying","instrumental": True,},)print(response.json()) # {"task_id": "..."}
Length
A song is usually two to four minutes long and never longer than 4 minutes 45 seconds. To ask for a different length, set length_range to the shortest and longest length you want, in seconds.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A short, punchy pop-punk song about Mondays","length_range": [60, 120],},)print(response.json()) # {"task_id": "..."}
The range is a suggestion to the model, and the model generally follows it. A larger range gives a longer song, but some songs do not follow the range. If you send your own lyrics, the amount of lyrics you send is a strong indicator of how long the song will be.
Clips
Set clip to true for a short piece that sounds like it was cut from the middle of a song. Without this option, our model tries to generate a complete song.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A catchy synth-pop hook for a sneaker ad","clip": True,},)print(response.json()) # {"task_id": "..."}
A clip is under 30 seconds. For a longer one, send length_range with it. If you send your own lyrics, send only the few lines the clip should sing. A clip costs the same credits as a song. clip is only valid for new generations, not extensions.
Two songs
Set num_songs to 2 and one request generates two different songs. Both songs will have the same styles and lyrics.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "An upbeat indie rock song about a road trip with old friends","num_songs": 2,},)print(response.json()) # {"task_ids": ["...", "..."]}
Each song is generated as a separate task, so the response includes task_ids instead of task_id:
{"task_ids": ["a598194b-d464-474c-b1e6-1c99f8f8e457","c41d7e02-9b3a-4f6d-8e15-2a7f0b6c93d8"]}
- A request for two songs creates two tasks, and each task has a different
task_id. When you request the result for eachtask_idwith GET /generations/{task_id}, thesong_pathsof that task includes one URL. - Each task is tracked in the same way as a task for a single song. Each task has its own status and its own stream.
- When using a
webhook_url, status updates for each task are separately sent to the same URL. Each POST request still includes thetask_idof the corresponding task. - A request for two songs costs 200 credits. If one of the songs fails, you are only charged for the song that succeeded.
- All other parameters in the request apply to both songs.
num_songsis also supported when extending a song or generating from reference audio.
Parameters in this section
promptstringinstrumentalbooleanDefault: falselyrics with it.length_range[integer, integer][shortest, longest] length you want for the song, in seconds. This is a suggestion to the model and it generally follows it. Both values are multiples of 30. The first is 0 to 270, the second is 30 to 300, and the first must be lower than the second. The model never generates more than 4 minutes 45 seconds in one request.clipbooleanDefault: falselength_range.num_songsintegerDefault: 1task_ids instead of task_id.These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Use your own lyrics
Send the lyrics and a prompt that describes how the song should sound.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "Dreamy indie pop with a big singalong chorus","lyrics": "[Verse]\nHeadlights on an empty road\nRadio is singing low\n\n[Chorus]\nWe are going where the map runs out\nWe are going where the map runs out",},)print(response.json()) # {"task_id": "..."}
The lyrics in that request, written out:
[Verse]Headlights on an empty roadRadio is singing low[Chorus]We are going where the map runs outWe are going where the map runs out
- Label sections in square brackets, such as
[Verse]and[Chorus], with each label on its own line. - Send lyrics with either a
promptortags, but not both. The API rejects lyrics sent alone. - The amount of lyrics you send is a strong indicator of how long the song will be.
- Lyrics can be up to 40,000 characters, but they must also fit in one song. If they do not, the API rejects the request or the task fails with "Prompt (tags + lyrics) too long".
Parameters in this section
promptstringlyricsstringprompt or tags. Up to 40,000 characters.These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Choose the style
We normally pick a song's style tags from your prompt. Send tags to pick them yourself.
Tags are short labels such as a genre, a mood, or an instrument. They must come from our tag list. We recommend sending at least three.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A song about leaving your hometown","tags": ["indie rock", "female vocalist", "melancholic"],},)print(response.json()) # {"task_id": "..."}
In that request we use the prompt only to write the lyrics. To set both the style and the lyrics yourself, send tags and lyrics with no prompt:
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"tags": ["indie rock", "female vocalist", "melancholic"],"lyrics": "[Verse]\nHeadlights on an empty road\nRadio is singing low\n\n[Chorus]\nWe are going where the map runs out\nWe are going where the map runs out",},)print(response.json()) # {"task_id": "..."}
What you send and what we write
| You send | We write |
|---|---|
| prompt | Tags and lyrics |
| prompt + lyrics | Tags |
| prompt + tags | Lyrics |
| tags + lyrics | Nothing |
| tags + instrumental | Nothing |
| prompt + instrumental | Tags |
The API rejects any other combination, such as prompt, tags, and lyrics together, lyrics alone, or tags alone without instrumental. To send tags and let us decide what the lyrics are about, add "prompt": "".
Avoid a style
List the tags you want the song to avoid in negative_tags. A higher negative_tags_strength makes the model avoid them more.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A slow acoustic song about leaving your hometown","negative_tags": ["electronic", "drum machine"],"negative_tags_strength": 2,},)print(response.json()) # {"task_id": "..."}
How closely the song follows the style
Higher values of style_scale and prompt_strength make the song follow your tags and lyrics more closely but sound less natural. We tuned the defaults, so change them only if songs ignore what you asked for. Only one of the two can be above 1.0. We strongly discourage setting either above 3.0, or negative_tags_strength above 5.0. Higher values will likely give lower quality results.
Parameters in this section
tagsarray of stringsnegative_tagsarray of stringsnegative_tags_strengthfloatDefault: 1.0negative_tags. 1.0 to 10.0. We strongly discourage values above 5.0, which will likely give lower quality results. You can change it only if you send negative_tags.style_scalefloatDefault: 2.3prompt_strengthfloatDefault: 1.0prompt_strength and style_scale must be above 1.0, so set style_scale to 1.0 before you raise this.These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Use a model variant
A variant is a version of the model with its own sound.
List the variant you want in variants. Without the field, we use the standard model.
| Variant | Sound |
|---|---|
s-punchy | Harder-hitting, more dance/pop-oriented sound |
s-smooth | Catchy and mellow pop-oriented sound |
s-squishy | Squishy drums, a bouncy groove, and happy accidents |
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "An upbeat synth-pop song about a road trip","variants": ["s-punchy"],},)print(response.json()) # {"task_id": "..."}
- Variants are in beta. We may add or remove a variant at any time.
variantsworks on every v3 request: generating, extending, covering, using a voice, and transferring a style.- A variant changes only the sound. It takes the same tags and costs the same credits.
- The field is a list, so you can combine variants by sending more than one.
- An extend does not reuse the variants of the song it continues. To keep the same sound, send
variantsagain. - GET /generations/{task_id} returns the variants a task used in
v3_params.variants.
Parameters in this section
variantsarray of stringss-punchy, s-smooth, and s-squishy, each at most once. Leave the field out to use the standard model.These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Upload audio
To extend a song, cover a song, use a voice, or transfer a style, you send us audio. There are three ways to send it.
audio_urlstring (URL)song_paths.audio_upload_idstring (UUID)POST /uploads returns. It expires after about 24 hours.audio_base64stringSend exactly one of the three.
Using a song you generated with the API
song_paths as audio_url instead of downloading and uploading the file. We then use our stored copy of the song, so the audio does not lose quality with each request.Uploading a file
If the audio is not at a public URL, upload it and pass the id from the response. We accept mp3, m4a, ogg, flac, wav, amr, aac, and aiff files of up to 40MB.
import requests# 1. Upload the filewith open("my-song.mp3", "rb") as f:upload = requests.post("https://api.treblo.com/v1/uploads",headers={"Authorization": "Bearer your_api_key_here"},files={"file": f},)audio_upload_id = upload.json()["audio_upload_id"]# 2. Use itresponse = requests.post("https://api.treblo.com/v1/generations/v3/extend",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_upload_id": audio_upload_id,"prompt": "Add a guitar solo, then one last chorus",},)print(response.json()) # {"task_id": "..."}
- You can use an upload in any number of requests until it expires, about 24 hours after you upload it.
- Keep the id private, because anyone who has it can use the upload.
Extend a song
Continue a song from where it ends. The result is the whole song, with the new part after the original.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3/extend",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg","prompt": "Add a guitar solo, then one last chorus",},)print(response.json()) # {"task_id": "..."}
The prompt describes what happens next. As with a new song, you can also send lyrics for the new part or set the tags.
Continue from before the ending
A finished song usually has an outro. Set crop_duration to cut that many seconds from the end before the model continues the song:
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3/extend",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg","prompt": "Replace the fade-out with a bridge and a final chorus","crop_duration": 12,},)print(response.json()) # {"task_id": "..."}
Make room for a longer new part
Before it continues, the model listens to the end of your song, up to 150 seconds by default. That context and the new audio together cannot be longer than 4 minutes 45 seconds, so the default leaves up to 2 minutes 15 seconds for the new part. To get a longer new part, lower context_seconds. Less context leaves more room for new audio but keeps the new part less close to the original.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3/extend",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg","prompt": "Add two more verses and a long outro","context_seconds": 60,},)print(response.json()) # {"task_id": "..."}
Parameters in this section
context_secondsfloatDefault: 150crop_durationfloatDefault: 0These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Cover a song
Make a new version of a song that keeps its melody, for example in another genre or with other lyrics.
A cover is a request to /generations/v3/reference with reference_mode: "cover".
import requests# 1. Upload the filewith open("original.mp3", "rb") as f:upload = requests.post("https://api.treblo.com/v1/uploads",headers={"Authorization": "Bearer your_api_key_here"},files={"file": f},)audio_upload_id = upload.json()["audio_upload_id"]# 2. Use itresponse = requests.post("https://api.treblo.com/v1/generations/v3/reference",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_upload_id": audio_upload_id,"reference_mode": "cover","prompt": "A slow acoustic version with fingerpicked guitar",},)print(response.json()) # {"task_id": "..."}
- The
promptdescribes the new version. Send an empty string to let us decide. - If you send no
lyrics, we transcribe the original and write new lyrics in its style. To keep the original lyrics, send them aslyrics. - Set
instrumentalto true for a version with no vocals. reference_scalehas a large effect. If the cover does not follow the original closely enough, raise it.
Choose the part to cover
By default the model listens to the first 90 seconds of the audio. Choose another part with reference_crop_start and reference_crop_end. For a cover, the reference audio must be 12 to 284.7 seconds long (about 4 minutes 45 seconds). The new song can also be up to 4 minutes 45 seconds long.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3/reference",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg","reference_mode": "cover","prompt": "A slow acoustic version with fingerpicked guitar","reference_crop_start": 30,"reference_crop_end": 120,"reference_scale": 2,},)print(response.json()) # {"task_id": "..."}
Parameters in this section
reference_crop_startfloatreference_crop_end.reference_crop_endfloatreference_scalefloatDefault: 1.0, or 4.0 for a voiceThese are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Use a voice
Generate a new song sung in the voice from a recording.
Send a recording of the singer to /generations/v3/reference with reference_mode: "voice". Your prompt, lyrics, and tags decide the rest of the song, as in any other request.
import requests# 1. Upload the filewith open("my-voice.wav", "rb") as f:upload = requests.post("https://api.treblo.com/v1/uploads",headers={"Authorization": "Bearer your_api_key_here"},files={"file": f},)audio_upload_id = upload.json()["audio_upload_id"]# 2. Use itresponse = requests.post("https://api.treblo.com/v1/generations/v3/reference",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_upload_id": audio_upload_id,"reference_mode": "voice","prompt": "A soulful ballad about coming home",},)print(response.json()) # {"task_id": "..."}
When the recording is a full song
If the audio has instruments as well as the singer, set voice_from_song to true and we separate the vocals first. We always do this for a song that this API generated.
import requests# 1. Upload the filewith open("my-song.mp3", "rb") as f:upload = requests.post("https://api.treblo.com/v1/uploads",headers={"Authorization": "Bearer your_api_key_here"},files={"file": f},)audio_upload_id = upload.json()["audio_upload_id"]# 2. Use itresponse = requests.post("https://api.treblo.com/v1/generations/v3/reference",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_upload_id": audio_upload_id,"reference_mode": "voice","voice_from_song": True,"reference_crop_start": 45,"reference_crop_end": 105,"prompt": "A soulful ballad about coming home",},)print(response.json()) # {"task_id": "..."}
- We use the singing in the first 75 seconds, unless you choose a part with
reference_crop_startandreference_crop_end. The part must be 10 to 75 seconds long and contain singing. reference_scalehas a large effect. If the new song does not keep enough of the voice, raise it. For a voice it defaults to 4.0 and can be up to 7.0.- To use a voice again, upload the recording once and reuse its
audio_upload_id. Later requests with the same upload and the same part of it can skip the step that prepares the voice.
Parameters in this section
voice_from_songbooleanDefault: falsereference_mode: "voice". Set to true when the audio is a full song and not a recording of only the singer.These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Transfer a style
Generate a new song with the vocals and instruments of a reference but a new melody and new lyrics.
Send the reference to /generations/v3/reference with reference_mode: "style".
import requests# 1. Upload the filewith open("reference.mp3", "rb") as f:upload = requests.post("https://api.treblo.com/v1/uploads",headers={"Authorization": "Bearer your_api_key_here"},files={"file": f},)audio_upload_id = upload.json()["audio_upload_id"]# 2. Use itresponse = requests.post("https://api.treblo.com/v1/generations/v3/reference",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_upload_id": audio_upload_id,"reference_mode": "style","prompt": "A song about a rainy day in the city",},)print(response.json()) # {"task_id": "..."}
- Unlike a cover, the new song does not follow the reference's melody or lyrics. We write the lyrics from your prompt unless you send
lyrics. - The model listens to the first 90 seconds, unless you choose a part with
reference_crop_startandreference_crop_end. For a style, the reference audio can be 12 to 284.7 seconds long (about 4 minutes 45 seconds). The new song can also be up to 4 minutes 45 seconds long. reference_scalehas a large effect. If the song does not sound enough like the reference, raise it.
Replace a section
Regenerate one part of a song and keep the rest.
Only on our older model for now
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v2/inpaint",headers={"Authorization": "Bearer your_api_key_here"},json={"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg","tags": ["rock", "energetic"],"sections": [[20, 35]],"lyrics": "The new words for these fifteen seconds",},)print(response.json()) # {"task_id": "..."}
sectionsholds the start and end, in seconds, of the part to replace.lyricsare the lyrics for the new part. For a part with no vocals, leave them out and setinstrumentalto true.tagsare required, and this endpoint does not accept aprompt.- Set
num_songsto 2 to get two versions. On v2, both versions are generated by a single task, and thesong_pathsof that task includes two URLs, one for each version.
Parameters in this section
sections[[float, float]]required[start, end] of the part to replace, in seconds. The part must be at least 0.1 seconds long. Send exactly 1 section.selection_cropbooleanDefault: falselyricsstringinstrumental to true. Up to 40,000 characters.tagsarray of stringsrequiredThese are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Track progress
Each generation is a task with a status. Poll the status, or give us a webhook URL and we send each change to you.
We recommend webhooks over polling because they are more efficient.
Polling
GET /generations/status/{task_id} returns the current status as a JSON string, as in the quick start. Once it is SUCCESS, GET /generations/{task_id} returns the song's URLs in song_paths with the lyrics and tags the song was generated with.
Statuses
These are the statuses a task can have, in the order they happen. A task skips the ones that do not apply to it, so wait for SUCCESS or FAILURE.
RECEIVEDTRANSCRIBE_TASK_STARTEDrequests with audioPROMPTTASK_SENTGENERATE_TASK_STARTEDLOADING_SOURCEv2 extend and replaceBEGINNING_GENERATIONGENERATINGGENERATING_STREAMING_READYv3DECOMPRESSINGSAVINGSUCCESSFAILUREReceive webhooks
Give us a URL and we POST each status change of the task to it.
Add a webhook_url to any request. Each POST is JSON with the task_id and the new status. The POST for SUCCESS contains the song. A POST about lyrics alignment has alignment_status in place of status.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A chill lofi beat for studying","webhook_url": "https://example.com/treblo-webhook",},)print(response.json()) # {"task_id": "..."}
{"task_id": "a598194b-d464-474c-b1e6-1c99f8f8e457","status": "SUCCESS","song_paths": ["https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg"]}
Answer each POST with a 2xx status within 10 seconds. We count any other answer, or no answer, as a failed delivery.
Check that a webhook is from us
We sign every webhook with your account's signing secret. The secret is on the API Keys page of your account. Each webhook has three headers:
webhook-idwebhook-timestampwebhook-signatureThe headers follow the Standard Webhooks format, so a Standard Webhooks library can check them:
# pip install standardwebhooksfrom standardwebhooks import Webhook, WebhookVerificationErrorwebhook = Webhook("whsec_your_signing_secret")def handle_webhook(body: bytes, headers: dict) -> int:"""Takes the raw request body and the request headers. Returns the status to answer with."""try:update = webhook.verify(body, headers)except WebhookVerificationError:return 400 # We did not send thisprint(update["task_id"], update.get("status"))return 204
- Check the raw request body. If you parse the JSON and write it out again, the bytes change and the check fails.
- The libraries reject a webhook whose timestamp is more than 5 minutes from the current time.
- To check a webhook without a library, compute the HMAC-SHA256 of
{webhook-id}.{webhook-timestamp}.{body}. The key is the part of the secret afterwhsec_, decoded from base64. The signature is that HMAC in base64. - If you rotate the secret on the API Keys page, the old secret stops working right away.
Retries
When a webhook delivery fails (non-2xx status code or timeout), we try to send the webhook again only for SUCCESS, FAILURE, and GENERATING_STREAMING_READY status updates (includes lyrics alignment). All other statuses are not retried since they are ephemeral.
- For
SUCCESSandFAILURE, we retry up to 5 times. The wait times before the retries are 30 seconds, 2 minutes, 10 minutes, 1 hour, and 3 hours. - We retry
GENERATING_STREAMING_READYat most 2 times, and only while the song is still generating. - A retry has the same
webhook-idas the first delivery. Use the id to skip a webhook you have already handled. - A retry can arrive after the webhook for a later status. Once a task is
SUCCESSorFAILURE, ignore a webhook that reports any otherstatusfor it. - If the last retry fails, we stop. Poll for a status you did not receive.
Stream while generating
Play a song while we are still generating it.
- Set
enable_streamingto true on a v3 request. - Wait for the status
GENERATING_STREAMING_READY. - Play
https://api-stream.treblo.com/stream/{task_id}. The URL needs no API key, so you can use it as the source of an audio element.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A chill lofi beat for studying","enable_streaming": True,},)print(response.json()) # {"task_id": "..."}
<!-- Works once the task reaches GENERATING_STREAMING_READY --><audio controls autoplay><source src="https://api-stream.treblo.com/stream/your_task_id" type="audio/ogg" /></audio>
- If you connect late, you first receive the audio generated so far and then the rest as we generate it.
- The stream is Opus in an ogg container unless you set
stream_formatto mp3. Extend requests always stream ogg. - The stream ends a few seconds after the song is finished. You can still open it for 150 seconds after that. Past that point, use the file in
song_paths. - For a request with two songs, each task has its own stream.
- Streaming does not change what a request costs.
Align the lyrics
Get the start and end time of every word, for example to show lyrics in time with the song.
Set align_lyrics to true on any request. After the song is finished, we align its lyrics to the audio in a second step that has its own status.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "An upbeat indie rock song about a road trip with old friends","align_lyrics": True,},)print(response.json()) # {"task_id": "..."}
- Wait for the song to finish, then poll
/generations/status/{task_id}?include_alignment=trueuntilalignment_statusisSUCCESS. Stop if it becomesFAILURE. Webhook updates also includealignment_status. - Fetch the task. The timings are in
word_aligned_lyrics(null if the lyrics could not be aligned):
[{"word": "Headlights","start": 12.48,"end": 13.02},{"word": "on","start": 13.02,"end": 13.2}]
- We ignore
align_lyricsfor instrumentals, which have no lyrics to align. - If the song fails,
alignment_statusstaysREQUESTED, so checkstatusfirst. - If the song succeeds but the alignment fails, we still charge for the song.
Files and formats
Songs are Opus files in an ogg container unless you set output_format.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here"},json={"prompt": "A chill lofi beat for studying","output_format": "mp3","output_bit_rate": 320,},)print(response.json()) # {"task_id": "..."}
Parameters in this section
output_formatstringDefault: oggoutput_bit_rateintegerThese are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.
Download the songs you want to keep
Retry a request safely
Send an Idempotency-Key header, and a repeat of the request returns the first task. It does not create a second song.
import requestsresponse = requests.post("https://api.treblo.com/v1/generations/v3",headers={"Authorization": "Bearer your_api_key_here","Idempotency-Key": "6f1c9a4e-2d0b-4f3a-9c1e-8a7b5d3e2f10",},json={"prompt": "A chill lofi beat for studying",},)print(response.json()) # {"task_id": "..."}
Choose a new key for each request, such as a UUID, and send the same key every time you repeat that request. A key is 1 to 255 characters. Every endpoint that starts a generation accepts the header.
- The first request with a key creates the task. A later request from your account with the same key returns the same
task_id, and we charge you once. If the request was for two songs, repeating the request returns the same twotask_ids. - Repeat a request with its key when it times out, the connection drops, or the API answers with a 5xx status.
- A key keeps returning the task it created and does not expire. If that task ends in
FAILURE, send a new key to try the song again. - A request that the API rejects creates no task, so you can correct it and send it again with the same key.
- A repeat must go to the same endpoint with the same body, byte for byte. A body with its fields in another order counts as a different request. If you use the same idempotency key with a different request, the API will respond with a 422.