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

# 快速接入指南

> 5 分钟完成首个 SenseAudio 请求

export const PlatformLink = ({href, children}) => {
  const MOBILE_MAX_WIDTH = 768;
  const TOAST_TEXT = '为了更好的支付体验，请在电脑端进行操作';
  const TOAST_DURATION_MS = 2400;
  const [toastVisible, setToastVisible] = useState(false);
  const hideTimerRef = useRef(0);
  useEffect(() => {
    return () => {
      if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    };
  }, []);
  const handleClick = event => {
    const isMobile = typeof window !== 'undefined' && window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH - 1}px)`).matches;
    if (!isMobile) return;
    event.preventDefault();
    event.stopPropagation();
    setToastVisible(true);
    if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    hideTimerRef.current = window.setTimeout(() => {
      setToastVisible(false);
    }, TOAST_DURATION_MS);
  };
  return <>
      <a href={href} onClick={handleClick} target="_blank" rel="noreferrer" className="text-primary">
        {children}
      </a>
      {toastVisible && <div role="status" aria-live="polite" className="fixed left-1/2 bottom-20 -translate-x-1/2 max-w-[calc(100vw-32px)] px-5 py-3 bg-black/85 text-white text-sm leading-normal rounded-lg shadow-lg z-[99999] text-center pointer-events-none">
          {TOAST_TEXT}
        </div>}
    </>;
};

本指南以语音合成能力为例，帮助您在 5 分钟内完成首个 API 调用，并直接得到可播放的 `mp3` 文件。

## 1. 获取密钥 (API Key)

<Steps>
  <Step title="进入 API 密钥">
    进入 [API 密钥](https://senseaudio.cn/api-platform/api-key) 页面。
  </Step>

  <Step title="新增并保存 API Key">
    点击 **"新增 API Key"**，复制并安全保存您的 API Key。
  </Step>
</Steps>

## 2. 发起请求

选择您熟悉的编程语言，复制以下示例即可直接运行。

> 以下示例统一输出 `output.mp3`。其中 `model` 需填写模型名称，`voice_setting.voice_id` 需填写可调用音色 ID。

<Tabs>
  <Tab title="CURL">
    ```bash theme={null}
    curl -X POST https://api.senseaudio.cn/v1/t2a_v2 \
      -H "Authorization: Bearer $SENSEAUDIO_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "senseaudio-tts-1.5-260319",
        "text": "你好，这是来自 SenseAudio 的第一条语音。",
        "voice_setting": {
          "voice_id": "male_0004_a"
        },
        "audio_setting": {
          "format": "mp3",
          "sample_rate": 32000
        }
      }' -o response.json

    jq -r '.data.audio' response.json | xxd -r -p > output.mp3
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    # 1. 配置 API Key 和 URL
    SENSEAUDIO_API_KEY = "SENSEAUDIO_API_KEY"
    url = "https://api.senseaudio.cn/v1/t2a_v2"

    # 2. 准备请求数据
    payload = {
        "model": "senseaudio-tts-1.5-260319",
        "text": "你好，这是来自 SenseAudio 的第一条语音。",
        "voice_setting": {
            "voice_id": "male_0004_a",
            "speed": 1.0,
            "vol": 1.0,
            "pitch": 0
        },
        "audio_setting": {
            "format": "mp3",
            "sample_rate": 32000
        }
    }

    headers = {
        "Authorization": f"Bearer {SENSEAUDIO_API_KEY}",
        "Content-Type": "application/json"
    }

    # 3. 发送请求
    response = requests.post(url, json=payload, headers=headers)
    result = response.json()

    if result.get("data") and result["data"].get("audio"):
        audio_bytes = bytes.fromhex(result["data"]["audio"])
        with open("output.mp3", "wb") as f:
            f.write(audio_bytes)
        print("语音已保存到 output.mp3")
    else:
        print(f"请求失败: {result.get('base_resp', {}).get('status_msg', 'unknown error')}")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const axios = require('axios');
    const fs = require('fs');

    const SENSEAUDIO_API_KEY = "SENSEAUDIO_API_KEY";
    const url = 'https://api.senseaudio.cn/v1/t2a_v2';

    const payload = {
      model: 'senseaudio-tts-1.5-260319',
      text: '你好，这是来自 SenseAudio 的第一条语音。',
      voice_setting: {
        voice_id: 'male_0004_a',
        speed: 1.0,
        vol: 1.0,
        pitch: 0
      },
      audio_setting: {
        format: 'mp3',
        sample_rate: 32000
      }
    };

    axios.post(url, payload, {
      headers: {
        'Authorization': `Bearer ${SENSEAUDIO_API_KEY}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => {
      const result = response.data;

      if (result.data?.audio) {
        const audioBuffer = Buffer.from(result.data.audio, 'hex');
        fs.writeFileSync('output.mp3', audioBuffer);
        console.log('语音已保存到 output.mp3');
      } else {
        console.error('请求失败:', result.base_resp?.status_msg || 'unknown error');
      }
    })
    .catch(error => {
      console.error('请求失败:', error.message);
    });
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

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

    type TTSRequest struct {
        Model         string        `json:"model"`
        Text          string        `json:"text"`
        VoiceSetting  VoiceSetting  `json:"voice_setting"`
        AudioSetting  AudioSetting  `json:"audio_setting"`
    }

    type VoiceSetting struct {
        VoiceID string  `json:"voice_id"`
        Speed   float64 `json:"speed"`
        Vol     float64 `json:"vol"`
        Pitch   int     `json:"pitch"`
    }

    type AudioSetting struct {
        Format     string `json:"format"`
        SampleRate int    `json:"sample_rate"`
    }

    func main() {
        SENSEAUDIO_API_KEY := "SENSEAUDIO_API_KEY"
        url := "https://api.senseaudio.cn/v1/t2a_v2"

        payload := TTSRequest{
            Model: "senseaudio-tts-1.5-260319",
            Text:  "你好，这是来自 SenseAudio 的第一条语音。",
            VoiceSetting: VoiceSetting{
                VoiceID: "male_0004_a",
                Speed:   1.0,
                Vol:     1.0,
                Pitch:   0,
            },
            AudioSetting: AudioSetting{
                Format:     "mp3",
                SampleRate: 32000,
            },
        }

        jsonData, _ := json.Marshal(payload)
        req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
        req.Header.Set("Authorization", "Bearer "+SENSEAUDIO_API_KEY)
        req.Header.Set("Content-Type", "application/json")

        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            fmt.Println("请求失败:", err)
            return
        }
        defer resp.Body.Close()

        body, _ := io.ReadAll(resp.Body)
        var result map[string]any
        json.Unmarshal(body, &result)

        data, ok := result["data"].(map[string]any)
        if !ok || data["audio"] == nil {
            fmt.Println("请求失败")
            return
        }

        audioHex, _ := data["audio"].(string)
        audioBytes, err := hex.DecodeString(audioHex)
        if err != nil {
            fmt.Println("音频解码失败:", err)
            return
        }

        os.WriteFile("output.mp3", audioBytes, 0644)
        fmt.Println("语音已保存到 output.mp3")
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import org.json.JSONObject;

    public class SenseAudioQuickStart {
        public static void main(String[] args) {
            try {
                String SENSEAUDIO_API_KEY = "SENSEAUDIO_API_KEY";
                String apiUrl = "https://api.senseaudio.cn/v1/t2a_v2";

                // 构建请求体
                JSONObject voiceSetting = new JSONObject();
                voiceSetting.put("voice_id", "male_0004_a");
                voiceSetting.put("speed", 1.0);
                voiceSetting.put("vol", 1.0);
                voiceSetting.put("pitch", 0);

                JSONObject audioSetting = new JSONObject();
                audioSetting.put("format", "mp3");
                audioSetting.put("sample_rate", 32000);

                JSONObject payload = new JSONObject();
                payload.put("model", "senseaudio-tts-1.5-260319");
                payload.put("text", "你好，这是来自 SenseAudio 的第一条语音。");
                payload.put("voice_setting", voiceSetting);
                payload.put("audio_setting", audioSetting);

                // 发送请求
                URL url = new URL(apiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Authorization", "Bearer " + SENSEAUDIO_API_KEY);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);

                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = payload.toString().getBytes("utf-8");
                    os.write(input, 0, input.length);
                }

                // 读取响应
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }

                    JSONObject result = new JSONObject(response.toString());
                    JSONObject data = result.optJSONObject("data");

                    if (data != null && data.has("audio")) {
                        byte[] audioBytes = hexStringToByteArray(data.getString("audio"));
                        try (FileOutputStream fos = new FileOutputStream("output.mp3")) {
                            fos.write(audioBytes);
                        }
                        System.out.println("语音已保存到 output.mp3");
                    } else {
                        JSONObject baseResp = result.optJSONObject("base_resp");
                        System.out.println("请求失败: " +
                            (baseResp != null ? baseResp.optString("status_msg", "unknown error") : "unknown error"));
                    }
                }
            } catch (Exception e) {
                System.out.println("请求失败: " + e.getMessage());
            }
        }

        private static byte[] hexStringToByteArray(String hex) {
            int len = hex.length();
            byte[] data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
            }
            return data;
        }
    }
    ```
  </Tab>
</Tabs>

## 3. 命名与取值说明

* **`model`**：填写模型名称，例如 `senseaudio-tts-1.5-260319`，可在 **[模型列表](/guides/account/model-list)** 中查询。
* **`voice_setting.voice_id`**：填写可调用音色 ID，可在 **[音色列表](/guides/voice/catalog)** 中获取。
* **`output.mp3`**：示例中的输出文件名，可按业务需要自行修改。

## 相关资源

<CardGroup cols={2}>
  <Card title="TTS API" icon="waveform-lines" href="/api-reference/endpoint/tts/synthesize">
    语音合成同步合成接口参数详解。
  </Card>

  <Card title="SSE 流式合成" icon="zap" href="/api-reference/endpoint/tts/synthesize-stream">
    Server-Sent Events 协议流式语音合成接口。
  </Card>

  <Card title="模型列表" icon="list" href="/guides/account/model-list">
    查看全部可调用模型与计费概览。
  </Card>

  <Card title="计费规则" icon="credit-card" href="/guides/account/billing">
    了解各项能力的积分消耗规则。
  </Card>
</CardGroup>
