> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apimart.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 样本转歌曲 (sample)

>  - 以样本为基础生成歌曲。
- 引用源音轨：`task_id` + `audio_index` 指定，无需记录任何上游 id
- 异步任务：提交返回 `task_id`，轮询 `GET /v1/music/tasks/:task_id` 获取结果 

<Info>
  **引用源音轨**：基于已有歌曲的操作无需记任何上游 id，只需传 `task_id`（产出源音轨那次任务的我方 task\_id）+ `audio_index`（结果 `music[]` 里第几首，1-based，默认 `1`）。
</Info>

<Warning>
  `custom` 决定哪些字段生效：写在错误模式下的字段会被上游**静默忽略**（不报错）。`custom=true` 时 `prompt`（歌词）、`title`、`tags`、`negative_tags`、`auto_lyrics`、`style_weight`、`weirdness_constraint`、`audio_weight` 生效，`gpt_description` 被忽略；`custom=false` 时只读 `gpt_description`（此时**必填**，缺了提交期直接返回 400）。`vocal_gender` 两种模式都生效。不传 `custom` 时后端按此顺序推断：有 `prompt` → `true`；无 `prompt` 但有 `gpt_description` → `false`；否则有 `tags`/`title` → `true`。
</Warning>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.apimart.ai/v1/music/generations/sample \
    -H 'Authorization: Bearer <token>' \
    -H 'Content-Type: application/json' \
    --data '{
      "model": "suno",
      "task_id": "task_01ABC",
      "audio_index": 1,
      "start_s": 0,
      "end_s": 8,
      "instrumental": false,
      "version": "v5",
      "tags": "upbeat pop"
    }'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.apimart.ai/v1/music/generations/sample"

  payload = {
      "model": "suno",
      "task_id": "task_01ABC",
      "audio_index": 1,
      "start_s": 0,
      "end_s": 8,
      "instrumental": False,
      "version": "v5",
      "tags": "upbeat pop"
  }

  headers = {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
  }

  response = requests.post(url, json=payload, headers=headers)

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/music/generations/sample";

  const payload = {
    model: "suno",
    task_id: "task_01ABC",
    audio_index: 1,
    start_s: 0,
    end_s: 8,
    instrumental: false,
    version: "v5",
    tags: "upbeat pop"
  };

  const headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io/ioutil"
      "net/http"
  )

  func main() {
      url := "https://api.apimart.ai/v1/music/generations/sample"

      payload := map[string]interface{}{
          "model": "suno",
          "task_id": "task_01ABC",
          "audio_index": 1,
          "start_s": 0,
          "end_s": 8,
          "instrumental": false,
          "version": "v5",
          "tags": "upbeat pop",
      }

      jsonData, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer <token>")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://api.apimart.ai/v1/music/generations/sample";

          String payload = """
          {
            "model": "suno",
            "task_id": "task_01ABC",
            "audio_index": 1,
            "start_s": 0,
            "end_s": 8,
            "instrumental": false,
            "version": "v5",
            "tags": "upbeat pop"
          }
          """;

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(payload))
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $url = "https://api.apimart.ai/v1/music/generations/sample";

  $payload = [
      "model" => "suno",
      "task_id" => "task_01ABC",
      "audio_index" => 1,
      "start_s" => 0,
      "end_s" => 8,
      "instrumental" => false,
      "version" => "v5",
      "tags" => "upbeat pop"
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>",
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://api.apimart.ai/v1/music/generations/sample")

  payload = {
    model: "suno",
    task_id: "task_01ABC",
    audio_index: 1,
    start_s: 0,
    end_s: 8,
    instrumental: false,
    version: "v5",
    tags: "upbeat pop"
  }

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(url)
  request["Authorization"] = "Bearer <token>"
  request["Content-Type"] = "application/json"
  request.body = payload.to_json

  response = http.request(request)
  puts response.body
  ```

  ```swift Swift theme={null}
  import Foundation

  let url = URL(string: "https://api.apimart.ai/v1/music/generations/sample")!

  let payload: [String: Any] = [
      "model": "suno",
      "task_id": "task_01ABC",
      "audio_index": 1,
      "start_s": 0,
      "end_s": 8,
      "instrumental": false,
      "version": "v5",
      "tags": "upbeat pop"
  ]

  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

  let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let error = error {
          print("Error: \(error)")
          return
      }

      if let data = data, let responseString = String(data: data, encoding: .utf8) {
          print(responseString)
      }
  }

  task.resume()
  ```

  ```csharp C# theme={null}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://api.apimart.ai/v1/music/generations/sample";

          var payload = @"{
              ""model"": ""suno"",
              ""task_id"": ""task_01ABC"",
              ""audio_index"": 1,
              ""start_s"": 0,
              ""end_s"": 8,
              ""instrumental"": false,
              ""version"": ""v5"",
              ""tags"": ""upbeat pop""
          }";

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

          var content = new StringContent(payload, Encoding.UTF8, "application/json");
          var response = await client.PostAsync(url, content);
          var result = await response.Content.ReadAsStringAsync();

          Console.WriteLine(result);
      }
  }
  ```

  ```c C theme={null}
  #include <stdio.h>
  #include <curl/curl.h>

  int main(void) {
      CURL *curl;
      CURLcode res;

      curl_global_init(CURL_GLOBAL_DEFAULT);
      curl = curl_easy_init();

      if(curl) {
          const char *url = "https://api.apimart.ai/v1/music/generations/sample";
          const char *payload = "{"
              "\"model\":\"suno\","
              "\"task_id\":\"task_01ABC\","
              "\"audio_index\":1,"
              "\"start_s\":0,"
              "\"end_s\":8,"
              "\"instrumental\":false,"
              "\"version\":\"v5\","
              "\"tags\":\"upbeat pop\""
          "}";

          struct curl_slist *headers = NULL;
          headers = curl_slist_append(headers, "Authorization: Bearer <token>");
          headers = curl_slist_append(headers, "Content-Type: application/json");

          curl_easy_setopt(curl, CURLOPT_URL, url);
          curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

          res = curl_easy_perform(curl);

          if(res != CURLE_OK) {
              fprintf(stderr, "curl_easy_perform() failed: %s\n",
                      curl_easy_strerror(res));
          }

          curl_slist_free_all(headers);
          curl_easy_cleanup(curl);
      }

      curl_global_cleanup();
      return 0;
  }
  ```

  ```objectivec Objective-C theme={null}
  #import <Foundation/Foundation.h>

  int main(int argc, const char * argv[]) {
      @autoreleasepool {
          NSURL *url = [NSURL URLWithString:@"https://api.apimart.ai/v1/music/generations/sample"];

          NSDictionary *payload = @{
              @"model": @"suno",
              @"task_id": @"task_01ABC",
              @"audio_index": @1,
              @"start_s": @0,
              @"end_s": @8,
              @"instrumental": @NO,
              @"version": @"v5",
              @"tags": @"upbeat pop"
          };

          NSError *error;
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload
                                                            options:0
                                                              error:&error];

          NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
          [request setHTTPMethod:@"POST"];
          [request setValue:@"Bearer <token>" forHTTPHeaderField:@"Authorization"];
          [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
          [request setHTTPBody:jsonData];

          NSURLSessionDataTask *task = [[NSURLSession sharedSession]
              dataTaskWithRequest:request
              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                      return;
                  }
                  NSString *result = [[NSString alloc] initWithData:data
                                                          encoding:NSUTF8StringEncoding];
                  NSLog(@"%@", result);
              }];

          [task resume];
          [[NSRunLoop mainRunLoop] run];
      }
      return 0;
  }
  ```

  ```ocaml OCaml theme={null}
  (* Requires cohttp and yojson libraries *)
  open Lwt
  open Cohttp
  open Cohttp_lwt_unix

  let url = "https://api.apimart.ai/v1/music/generations/sample"

  let payload = {|{
    "model": "suno",
    "task_id": "task_01ABC",
    "audio_index": 1,
    "start_s": 0,
    "end_s": 8,
    "instrumental": false,
    "version": "v5",
    "tags": "upbeat pop"
  }|}

  let () =
    let headers = Header.init ()
      |> fun h -> Header.add h "Authorization" "Bearer <token>"
      |> fun h -> Header.add h "Content-Type" "application/json"
    in
    let body = Cohttp_lwt.Body.of_string payload in

    let response = Client.post ~headers ~body (Uri.of_string url) >>= fun (resp, body) ->
      body |> Cohttp_lwt.Body.to_string >|= fun body_str ->
      print_endline body_str
    in
    Lwt_main.run response
  ```

  ```dart Dart theme={null}
  import 'dart:convert';
  import 'package:http/http.dart' as http;

  void main() async {
    final url = Uri.parse('https://api.apimart.ai/v1/music/generations/sample');

    final payload = {
      'model': 'suno',
      'task_id': 'task_01ABC',
      'audio_index': 1,
      'start_s': 0,
      'end_s': 8,
      'instrumental': false,
      'version': 'v5',
      'tags': 'upbeat pop'
    };

    final response = await http.post(
      url,
      headers: {
        'Authorization': 'Bearer <token>',
        'Content-Type': 'application/json',
      },
      body: jsonEncode(payload),
    );

    print(response.body);
  }
  ```

  ```r R theme={null}
  library(httr)
  library(jsonlite)

  url <- "https://api.apimart.ai/v1/music/generations/sample"

  payload <- list(
    model = "suno",
    task_id = "task_01ABC",
    audio_index = 1,
    start_s = 0,
    end_s = 8,
    instrumental = FALSE,
    version = "v5",
    tags = "upbeat pop"
  )

  response <- POST(
    url,
    add_headers(
      Authorization = "Bearer <token>",
      `Content-Type` = "application/json"
    ),
    body = toJSON(payload, auto_unbox = TRUE),
    encode = "raw"
  )

  cat(content(response, "text"))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "code": 200,
    "data": [
      {
        "status": "submitted",
        "task_id": "task_01K8SGYNNNVBQTXNR4MM964S7K"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "请求参数无效",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "身份验证失败，请检查您的API密钥",
      "type": "authentication_error"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "账户余额不足，请充值后再试",
      "type": "payment_required"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "访问被禁止，您没有权限访问此资源",
      "type": "permission_error"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "请求过于频繁，请稍后再试",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "服务器内部错误，请稍后重试",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "网关错误，服务器暂时不可用",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

## Authorizations

<ParamField header="Authorization" type="string" required>
  所有接口均需要使用Bearer Token进行认证

  获取 API Key：

  访问 [API Key 管理页面](https://apimart.ai/keys) 获取您的 API Key

  使用时在请求头中添加：

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

<ParamField body="model" type="string" default="suno">
  音频模型。当前传 `suno`（不传默认 `suno`）。
</ParamField>

<ParamField body="task_id" type="string" required>
  产出源音轨那次任务的我方 `task_id`（通常为上传的样本）。缺失或无法解析源时提交期直接返回 `400`。
</ParamField>

<ParamField body="audio_index" type="integer" default="1">
  引用源任务结果 `data.music[]` 中的第几首（1-based：1=第 1 首；默认 `1`；一次生成通常 2 首：索引 1 与 2）。
</ParamField>

<ParamField body="start_s" type="number" required>
  采样起点（秒；映射上游 `chop_sample_start_s`）。缺失直接返回 `400`，不打上游。
</ParamField>

<ParamField body="end_s" type="number" required>
  采样终点（秒；映射上游 `chop_sample_end_s`）。缺失直接返回 `400`，不打上游。
</ParamField>

<ParamField body="instrumental" type="boolean" default="false">
  是否纯器乐（`true`=无人声）；不传默认 `false`（要人声）。
</ParamField>

<ParamField body="version" type="string" default="v5.5">
  生成版本：`v3.5` / `v4` / `v4.5` / `v4.5+` / `v4.5-all` / `v5` / `v5.5`，影响音质与计费；不传默认 `v5.5`，非法值提交期直接返回 `400`。
</ParamField>

<ParamField body="custom" type="boolean">
  `true`=自定义模式（用 `prompt` 作歌词）；`false`=灵感模式（用 `gpt_description`）；不传时按内容推断（见上方 Warning）。
</ParamField>

<ParamField body="prompt" type="string">
  歌词，`custom=true` 时生效（灵感模式下会被忽略）。
</ParamField>

<ParamField body="gpt_description" type="string">
  灵感提示词，`custom=false` 时**必填**（缺了提交期直接 400、不打上游、不扣费）。
</ParamField>

<ParamField body="title" type="string">
  标题。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="tags" type="string">
  风格标签。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="negative_tags" type="string">
  要排除的风格标签。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="auto_lyrics" type="boolean">
  `true`=对输入歌词进行二次创作。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="style_weight" type="number">
  风格权重，`0.00`–`1.00`（越界提交期直接返回 `400`）。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="weirdness_constraint" type="number">
  创意权重，`0.00`–`1.00`（别名 `weirdness`）。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="audio_weight" type="number">
  音频权重，`0.00`–`1.00`。**仅 `custom=true` 时生效**。
</ParamField>

<ParamField body="vocal_gender" type="string">
  人声性别：`Male` / `Female`。**两种模式都生效**。
</ParamField>

<Note>
  **获取结果**：本接口为异步任务。提交后拿到 `task_id`，按 3–5s 间隔轮询 `GET /v1/music/tasks/{task_id}`，直到 `status` 为 `completed` 或 `failed`（音乐生成通常 30–120s；生成中 `status` 为 `pending`，`progress` 排队 10 → 就绪 50 → 完成 100）。完成后从 `data.result.music[]` 取 `audio_url`。失败时 `data.error.message` 给出原因，且预扣额度自动退回。
</Note>

## Response

<ResponseField name="code" type="integer">
  响应状态码
</ResponseField>

<ResponseField name="data" type="array">
  返回数据数组

  <Expandable title="属性">
    <ResponseField name="status" type="string">
      任务状态

      * `submitted` - 已提交
    </ResponseField>

    <ResponseField name="task_id" type="string">
      任务唯一标识符（用于轮询 `GET /v1/music/tasks/{task_id}` 获取结果）
    </ResponseField>
  </Expandable>
</ResponseField>
