# Add music to a post

List TikTok's trending commercial tracks for an account, schedule a video with one at the volume you want, and avoid the music conflicts.

TikTok posts made through the API can carry a track from TikTok's commercial music library. This script lists the trending tracks for an account and schedules a video with the top one, the track a little quieter than the video's own sound.

## Run it [#run-it]

You need an API key with the `accounts:read` and `posts:write` scopes. The video is a `mediaRef` from an upload (see [Upload a video and schedule it](/guides/upload-and-schedule)) or a public `https` link straight to the file. The country is optional.

```bash
export TIKTORNADO_API_KEY=<your key>
node add-music.mjs j971x2c4ajrq0w8sd5e8fxz3a57v2k8m https://media.example.com/uploads/7f3a9c/leg-day.mp4 2026-12-02T15:00:00Z US
```

```text
Track: Golden Hour by The Lanterns (7312345678901234567)
Saved post k174wq9nrm6t2f0bd3xh8pz5a87v1c2e for 2026-12-02T15:00:00.000Z
```

The Python script, `python3 add_music.py`, takes the same arguments and uses only the standard library.

## The code [#the-code]

<Tabs items={["Node.js","Python"]}>
<Tab value="Node.js">
```js title="add-music.mjs"
// Schedule a video with TikTok's number 1 trending commercial track for the account.
// Node.js 22 or later, nothing to install.
//
//   export TIKTORNADO_API_KEY=<your key>
//   node add-music.mjs <accountId> <video> <time> [country]
//
// <video> is a mediaRef from an upload, or a public https link straight to the file.
// <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
// [country] is two capital letters, such as GB. Left out, the account's own country.
import { randomUUID } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";

const API = process.env.TIKTORNADO_API_URL ?? "https://api.tiktornado.com/api/v1";
const KEY = process.env.TIKTORNADO_API_KEY;
// api() tries a request at most this many times, waiting this long between tries
// unless the answer says how long (Retry-After).
const ATTEMPTS = 5;
const RETRY_WAIT_MS = 5000;

class ApiError extends Error {
  constructor(status, error) {
    super(`${status} ${error.reason}: ${error.message}`);
    this.status = status;
    this.reason = error.reason;
  }
}

// One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
// same request again, Idempotency-Key and body included, so a change is never made twice.
async function api(method, path, body, idempotencyKey) {
  const headers = { Authorization: `Bearer ${KEY}` };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  const text = body === undefined ? undefined : JSON.stringify(body);
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(API + path, { method, headers, body: text });
    } catch (error) {
      if (attempt === ATTEMPTS) throw error;
      await sleep(RETRY_WAIT_MS);
      continue;
    }
    const answer = await res.json().catch(() => null);
    if (res.ok) return answer;
    const error = answer?.error ?? { reason: "unknown_error", message: `HTTP ${res.status}` };
    if (attempt === ATTEMPTS || !(res.status === 429 || res.status === 409 || res.status >= 500)) throw new ApiError(res.status, error);
    await sleep(res.status === 429 ? Number(res.headers.get("retry-after") ?? 60) * 1000 : RETRY_WAIT_MS);
  }
}

const [accountId, video, scheduledFor, country] = process.argv.slice(2);
if (!KEY || !accountId || !video || !scheduledFor) {
  console.error("Set TIKTORNADO_API_KEY, then: node add-music.mjs <accountId> <video> <time> [country]");
  process.exit(1);
}

try {
  // TikTok's top 100 for that country, rank 1 first. Ask for the account the post is for.
  const query = country ? `?${new URLSearchParams({ country })}` : "";
  const { tracks } = await api("GET", `/accounts/${accountId}/music${query}`);
  const track = tracks[0];
  if (!track) throw new Error("TikTok has no tracks for this account right now.");
  console.log(`Track: ${track.name} by ${track.artist || "an unknown artist"} (${track.id})`);

  // The track at 40, the video's own sound at 80. Both are 50 if left out.
  const settings = { music: { trackId: track.id, volume: 40, videoSoundVolume: 80 } };
  const post = await api("POST", "/posts", { accountId, kind: "video", mediaRefs: [video], scheduledFor, settings }, randomUUID());
  console.log(`Saved post ${post.id} for ${post.scheduledFor}`);
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
```
</Tab>

<Tab value="Python">
```python title="add_music.py"
# Schedule a video with TikTok's number 1 trending commercial track for the account.
# Python 3.9 or later, standard library only.
#
#   export TIKTORNADO_API_KEY=<your key>
#   python3 add_music.py <accountId> <video> <time> [country]
#
# <video> is a mediaRef from an upload, or a public https link straight to the file.
# <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
# [country] is two capital letters, such as GB. Left out, the account's own country.
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

API = os.environ.get("TIKTORNADO_API_URL", "https://api.tiktornado.com/api/v1")
KEY = os.environ.get("TIKTORNADO_API_KEY")
# api() tries a request at most this many times, waiting this long between tries
# unless the answer says how long (Retry-After).
ATTEMPTS = 5
RETRY_WAIT_SECONDS = 5

class ApiError(Exception):
    def __init__(self, status, error):
        super().__init__(f"{status} {error['reason']}: {error['message']}")
        self.status = status
        self.reason = error["reason"]

def api(method, path, body=None, idempotency_key=None):
    """One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
    same request again, Idempotency-Key and body included, so a change is never made twice."""
    headers = {"Authorization": f"Bearer {KEY}"}
    if body is not None:
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    data = None if body is None else json.dumps(body).encode()
    for attempt in range(1, ATTEMPTS + 1):
        request = urllib.request.Request(API + path, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=60) as res:
                return json.load(res)
        except urllib.error.HTTPError as res:
            try:
                error = json.load(res)["error"]
            except (ValueError, KeyError):
                error = {"reason": "unknown_error", "message": f"HTTP {res.code}"}
            if attempt == ATTEMPTS or not (res.code in (409, 429) or res.code >= 500):
                raise ApiError(res.code, error) from None
            time.sleep(int(res.headers.get("Retry-After", "60")) if res.code == 429 else RETRY_WAIT_SECONDS)
        except OSError:
            if attempt == ATTEMPTS:
                raise
            time.sleep(RETRY_WAIT_SECONDS)

def main(account_id, video, scheduled_for, country=None):
    # TikTok's top 100 for that country, rank 1 first. Ask for the account the post is for.
    query = "?" + urllib.parse.urlencode({"country": country}) if country else ""
    tracks = api("GET", f"/accounts/{account_id}/music{query}")["tracks"]
    if not tracks:
        sys.exit("TikTok has no tracks for this account right now.")
    track = tracks[0]
    print(f"Track: {track['name']} by {track['artist'] or 'an unknown artist'} ({track['id']})")

    # The track at 40, the video's own sound at 80. Both are 50 if left out.
    settings = {"music": {"trackId": track["id"], "volume": 40, "videoSoundVolume": 80}}
    body = {"accountId": account_id, "kind": "video", "mediaRefs": [video], "scheduledFor": scheduled_for, "settings": settings}
    post = api("POST", "/posts", body, str(uuid.uuid4()))
    print(f"Saved post {post['id']} for {post['scheduledFor']}")

if __name__ == "__main__":
    args = sys.argv[1:]
    if not KEY or not 3 <= len(args) <= 4:
        sys.exit("Set TIKTORNADO_API_KEY, then: python3 add_music.py <accountId> <video> <time> [country]")
    try:
        main(*args)
    except (ApiError, OSError) as error:
        sys.exit(str(error))
```
</Tab>
</Tabs>

## Pick a track [#pick-a-track]

`GET /accounts/{accountId}/music` answers TikTok's top 100 trending commercial tracks, rank 1 first, for the `country` you name (two capital letters), else the account's own country, else TikTok's global chart. TikTok is asked live, so the list changes. Ask for the account the post is for, and pass a track's `id` as `settings.music.trackId`.

`GET /accounts/{accountId}/post-options` doesn't cover music: it answers privacy, comments, duets and stitches. See [Post settings](/posting/post-settings#check-what-the-account-allows).

## Set the volume and the part [#set-the-volume-and-the-part]

On a video, four more fields are optional:

| Field | Meaning |
| --- | --- |
| `volume` | The track's volume, 0 to 100. 50 if left out |
| `videoSoundVolume` | The video's own sound under the track, 0 to 100. 50 if left out |
| `startMs` | Where in the track to start, in milliseconds. 0 if left out |
| `endMs` | Where in the track to stop, after `startMs`. The video's end if left out |

This plays the track from 15 to 30 seconds over a video whose own sound is muted:

```json operation="POST /posts" kind="request"
{
  "accountId": "j971x2c4ajrq0w8sd5e8fxz3a57v2k8m",
  "kind": "video",
  "mediaRefs": ["https://media.example.com/uploads/7f3a9c/leg-day.mp4"],
  "scheduledFor": "2026-12-02T15:00:00Z",
  "settings": {
    "music": {
      "trackId": "7312345678901234567",
      "volume": 100,
      "videoSoundVolume": 0,
      "startMs": 15000,
      "endMs": 30000
    }
  }
}
```

## Photo posts [#photo-posts]

A photo post takes the track alone, with no volume and no part:

```json operation="POST /posts" kind="request"
{
  "accountId": "j971x2c4ajrq0w8sd5e8fxz3a57v2k8m",
  "kind": "photo",
  "mediaRefs": [
    "https://media.example.com/uploads/c4e017/prep-1.jpg",
    "https://media.example.com/uploads/c4e017/prep-2.jpg"
  ],
  "scheduledFor": "2026-12-03T12:00:00+01:00",
  "settings": { "music": { "trackId": "7312345678901234567" } }
}
```

Or let TikTok pick a recommended track with `autoMusic: true`, instead of `music`. It is for photo posts only:

```json operation="POST /posts" kind="request"
{
  "accountId": "j971x2c4ajrq0w8sd5e8fxz3a57v2k8m",
  "kind": "photo",
  "mediaRefs": [
    "https://media.example.com/uploads/c4e017/prep-1.jpg",
    "https://media.example.com/uploads/c4e017/prep-2.jpg"
  ],
  "scheduledFor": "2026-12-03T12:00:00+01:00",
  "settings": { "autoMusic": true }
}
```

## What can go wrong [#what-can-go-wrong]

The settings are checked before the post is saved, in this order: the kind of post first, then the conflicts, then the values. The first problem is the answer.

| Reason | When | What to do |
| --- | --- | --- |
| `setting_videos_only` | `volume`, `videoSoundVolume`, `startMs` or `endMs` on a photo post | Send the `trackId` alone |
| `setting_photos_only` | `autoMusic` on a video, with or without `music` | Pick a track with `music` |
| `music_conflict` | Both `music` and `autoMusic: true` on a photo post | Keep one |
| `auto_music_branded` | `autoMusic: true` with `brandedContent` other than `none` | Branded content can use a track from the list, but not automatic music |
| `invalid_post_setting` | A volume outside 0 to 100, a number that isn't whole, `endMs` not after `startMs`, or a blank `trackId` | Fix the value |
| `account_reconnecting` | The music list was asked for while the account is being reconnected to TikTok | Try the list again later. Posts are still taken |
| `track_unavailable` | TikTok wouldn't use the track when the post went out. The post is `failed` with this reason | Edit the post with another track and a new time |

A track is only checked against TikTok when the post goes out, so `track_unavailable` comes on the failed post in `GET /posts/{postId}`, not as an answer to `POST /posts`. Editing a failed post schedules it again, and `settings` replaces the whole set, so send every setting the post should keep and a time more than 10 minutes ahead:

```json operation="PATCH /posts/{postId}" kind="request"
{
  "settings": { "music": { "trackId": "7312345678901234568", "volume": 40, "videoSoundVolume": 80 } },
  "scheduledFor": "2026-12-03T18:30:00Z"
}
```

Every other setting is on [Post settings](/posting/post-settings).