# Tạo giọng nói qua HTTP

POST /v1/audio/speech - nhận trọn file, stream PCM, hoặc Server-Sent Events.

`POST /v1/audio/speech` đọc `input` và trả audio trong cùng response. Có ba chế độ: trọn file (mặc định), stream PCM thô (`"stream": true`) và Server-Sent Events (`"stream_format": "sse"`).

Tham khảo đầy đủ: [Create speech](/docs-md/api-reference/speech/speech-create.md).

## Tham số

| Field | Kiểu | Mặc định | Ghi chú |
|---|---|---|---|
| `input` | string | (bắt buộc) | Chữ cần đọc, tối đa 5.000 ký tự (mặc định của deployment). Dài hơn: dùng [job bất đồng bộ](/docs-md/async-jobs.md). |
| `model` | string | `sota-voice-v1` | Chỉ có `sota-voice-v1`; có thể bỏ qua. Model khác: `404 model_not_found`. |
| `voice` | string | `default` | Giọng có sẵn hoặc `name` của giọng bạn đã nhân bản (ở bất kỳ `profile_state` nào). |
| `response_format` | string | `mp3` | `mp3`, `wav`, `opus`, `aac`, `flac`, `pcm`. Bỏ qua khi stream. |
| `stream` | boolean | `false` | `true`: trả PCM thô ngay khi sinh. |
| `stream_format` | string | | `sse`: trả `text/event-stream`. |
| `literal_punctuation` | boolean | | Đọc dấu câu thành chữ thay vì coi là ngữ điệu. |

Tách câu (`split_granularity`) chỉ có ở [WebSocket realtime](/docs-md/realtime-websocket.md); gửi field này qua HTTP: `400 invalid_request`.

Field `model`, `voice`, `input`, `stream`, `stream_format`, `response_format` không được lặp lại hoặc viết khác hoa thường (`Voice`): `400 invalid_request` với `param` là tên field.

## Trọn file

```bash tab="curl"
curl https://api.example.com/v1/audio/speech \
  -H "Authorization: Bearer $SOTA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"sota-voice-v1","voice":"default","input":"Chào mừng bạn đến với Sota Voice.","response_format":"wav"}' \
  --output speech.wav
```

```python tab="Python"
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.example.com/v1", api_key=os.environ["SOTA_API_KEY"])

with client.audio.speech.with_streaming_response.create(
    model="sota-voice-v1",
    voice="default",
    input="Chào mừng bạn đến với Sota Voice.",
    response_format="wav",
) as response:
    response.stream_to_file("speech.wav")
```

```js tab="JavaScript"
import fs from 'node:fs';
import OpenAI from 'openai';

const client = new OpenAI({ baseURL: 'https://api.example.com/v1', apiKey: process.env.SOTA_API_KEY });

const audio = await client.audio.speech.create({
  model: 'sota-voice-v1',
  voice: 'default',
  input: 'Chào mừng bạn đến với Sota Voice.',
  response_format: 'wav',
});
fs.writeFileSync('speech.wav', Buffer.from(await audio.arrayBuffer()));
```

`Content-Type` của response khớp `response_format`: `audio/mpeg`, `audio/wav`, `audio/ogg` (Opus), `audio/aac`, `audio/flac`, `audio/pcm`.

## Stream PCM

Với `"stream": true`, response là PCM thô (16-bit có dấu little-endian, mono, 44,1 kHz) gửi ngay khi đang sinh, thường bắt đầu sau 100-250 ms. Hợp để phát ngay mà không cần giải mã.

```bash tab="curl"
curl -N https://api.example.com/v1/audio/speech \
  -H "Authorization: Bearer $SOTA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"sota-voice-v1","voice":"default","input":"Đây là audio đang được stream.","stream":true}' \
  | ffplay -f s16le -ar 44100 -ch_layout mono -nodisp -autoexit -
```

```python tab="Python"
import os
import httpx  # pip install httpx

with httpx.stream(
    "POST",
    "https://api.example.com/v1/audio/speech",
    headers={"Authorization": f"Bearer {os.environ['SOTA_API_KEY']}"},
    json={"model": "sota-voice-v1", "voice": "default", "input": "Đây là audio đang được stream.", "stream": True},
    timeout=None,
) as r:
    r.raise_for_status()
    with open("speech.pcm", "wb") as out:
        for chunk in r.iter_bytes():
            out.write(chunk)  # hoặc đưa thẳng vào bộ phát
```

Một mẫu PCM (2 byte) có thể bị cắt giữa hai chunk; hãy giữ byte lẻ lại cho chunk sau.

## Server-Sent Events

Với `"stream_format": "sse"`, response là `text/event-stream`. Mỗi dòng `data:` là JSON: nhiều sự kiện `speech.audio.delta` (audio mã hóa base64 trong `audio`), rồi một `speech.audio.done`.

```bash
curl -N https://api.example.com/v1/audio/speech \
  -H "Authorization: Bearer $SOTA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"sota-voice-v1","voice":"default","input":"Xin chào.","stream_format":"sse"}'
```

```text
data: {"type":"speech.audio.delta","audio":"UklGRiQAAABXQVZF..."}

data: {"type":"speech.audio.delta","audio":"ZGF0YQAAAAAAAA=="}

data: {"type":"speech.audio.done"}
```

Giải mã base64 của từng `audio` và ghép theo thứ tự.

## Tính phí và lỗi

- Credit bị trừ trước, đúng số ký tự của `input`. Nếu dịch vụ giọng nói lỗi trước khi gửi byte đầu tiên, credit được hoàn lại (`503 upstream_unavailable`). Response kèm `x-credits-remaining`.
- Không đủ credit: `402 insufficient_credit`. Chữ quá dài: `400 input_too_long`. Body quá lớn: `413 request_too_large`.
- Request này tính vào giới hạn request/giây của khóa và số request realtime đồng thời của tài khoản. Xem [Giới hạn tốc độ](/docs-md/rate-limits.md) và [Mã lỗi](/docs-md/errors.md).

