# 文本转语音（流式与非流式）

> 音频生成

text 是逐字朗读的文本；风格指令写入 speech_metadata.style，瞬时标签可使用 <short pause> 或 <sigh>。双人请求中每个 part 的 speech_metadata.speaker 应匹配 speakerVoiceConfigs 中的 speaker。单人 voiceConfig 与 multiSpeakerVoiceConfig 不可同时设置。此文档仅给出示例音色，不声明音色列表或声音复刻接口的平台支持。

**流式请求**：本文档路径为非流式接口。如需流式响应，必须将请求路径中的 `generateContent` 替换为 `streamGenerateContent`，即 `/v1beta/models/gemini-3.8-flash-tts:streamGenerateContent`。请求头与请求体和非流式调用完全相同，无需添加 stream 字段。

## 请求地址

`POST https://api.modelverse.cn/v1beta/models/gemini-3.8-flash-tts:generateContent`

## 请求体

## 响应

- **200** — 非流式响应为完整音频：inlineData.mimeType 通常为 audio/wav，data 为带 RIFF 头的完整 WAV 的 Base64 编码，解码后可直接保存为 .wav 文件。
流式请求返回 text/event-stream，每个 data 都是本结构的 JSON 分片；音频分片为无头的原始 PCM（24 kHz、单声道、16 位有符号小端），需逐块 Base64 解码后拼接字节。
以下短 Base64 仅为结构示意，不是可播放的完整音频。
- **default** — 错误响应。

## OpenAPI 定义

```json
{
  "openapi": "3.1.0",
  "x-language": "zh-CN",
  "info": {
    "title": "gemini-3.8-flash-tts 流式与非流式语音接口文档",
    "version": "1.0.0",
    "description": "ModelVerse 上的 Gemini 兼容文本转语音（TTS）接口，模型将纯文本转换为单人或多人的音频。朗读风格可通过回合级元数据 `speech_metadata.style` 和文本中的内联标签控制，例如语气、韵律、节奏与音量。\n\ngemini-3.8-flash-tts 支持 130 种以上语言，输入语言由模型自动检测。非流式调用返回带 RIFF 头的完整 WAV 音频；流式调用（`:streamGenerateContent`）返回 SSE 事件流，每个事件的 `data` 为 `GenerateContentResponse` JSON 分片，音频分片为无头的原始 16 位有符号小端 PCM（24 kHz、单声道）。两种调用的请求体完全相同。"
  },
  "servers": [
    {
      "url": "https://api.modelverse.cn",
      "description": "中国大陆"
    },
    {
      "url": "https://api.umodelverse.ai",
      "description": "海外"
    },
    {
      "url": "https://api-us-ca.umodelverse.ai",
      "description": "美国洛杉矶"
    },
    {
      "url": "https://api-sg.umodelverse.ai",
      "description": "新加坡"
    },
    {
      "url": "https://api-ge-fra.umodelverse.ai",
      "description": "法兰克福"
    }
  ],
  "tags": [
    {
      "name": "gemini-3.8-flash-tts",
      "description": "文本转语音，支持单人朗读与多人对话，可结合 speech_metadata 与内联标签控制朗读风格。"
    }
  ],
  "security": [
    {
      "geminiApiKeyAuth": []
    }
  ],
  "externalDocs": {
    "description": "语音生成来源文档。",
    "url": "https://www.gemini-china-guide.com/docs/speech-generation?generate-content=true#streaming"
  },
  "paths": {
    "/v1beta/models/gemini-3.8-flash-tts:generateContent": {
      "post": {
        "tags": [
          "gemini-3.8-flash-tts"
        ],
        "operationId": "generateContentGemini38FlashTtsZhCN",
        "summary": "文本转语音（流式与非流式）",
        "description": "text 是逐字朗读的文本；风格指令写入 speech_metadata.style，瞬时标签可使用 <short pause> 或 <sigh>。双人请求中每个 part 的 speech_metadata.speaker 应匹配 speakerVoiceConfigs 中的 speaker。单人 voiceConfig 与 multiSpeakerVoiceConfig 不可同时设置。此文档仅给出示例音色，不声明音色列表或声音复刻接口的平台支持。\n\n**流式请求**：本文档路径为非流式接口。如需流式响应，必须将请求路径中的 `generateContent` 替换为 `streamGenerateContent`，即 `/v1beta/models/gemini-3.8-flash-tts:streamGenerateContent`。请求头与请求体和非流式调用完全相同，无需添加 stream 字段。",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateContentRequest"
              },
              "examples": {
                "singleSpeaker": {
                  "summary": "单人朗读",
                  "description": "调用路径：`/v1beta/models/gemini-3.8-flash-tts:generateContent`。\n\n先将 MODELVERSE_API_KEY 环境变量设置为 Modelverse API key，然后执行：\n\n```bash\ncurl --request POST \\\n  'https://api.modelverse.cn/v1beta/models/gemini-3.8-flash-tts:generateContent' \\\n  --header \"x-goog-api-key: ${MODELVERSE_API_KEY}\" \\\n  --header 'Content-Type: application/json' \\\n  --data-raw '{\n  \"contents\": [\n    {\n      \"role\": \"user\",\n      \"parts\": [\n        {\n          \"text\": \"Have a wonderful day!\",\n          \"speech_metadata\": {\n            \"style\": \"cheerful and friendly\"\n          }\n        }\n      ]\n    }\n  ],\n  \"generationConfig\": {\n    \"responseModalities\": [\n      \"AUDIO\"\n    ],\n    \"speechConfig\": {\n      \"voiceConfig\": {\n        \"voice\": \"Kore\"\n      }\n    }\n  }\n}'\n```",
                  "value": {
                    "contents": [
                      {
                        "role": "user",
                        "parts": [
                          {
                            "text": "Have a wonderful day!",
                            "speech_metadata": {
                              "style": "cheerful and friendly"
                            }
                          }
                        ]
                      }
                    ],
                    "generationConfig": {
                      "responseModalities": [
                        "AUDIO"
                      ],
                      "speechConfig": {
                        "voiceConfig": {
                          "voice": "Kore"
                        }
                      }
                    }
                  }
                },
                "twoSpeakers": {
                  "summary": "双人对话",
                  "value": {
                    "contents": [
                      {
                        "role": "user",
                        "parts": [
                          {
                            "text": "Hello, Jane!",
                            "speech_metadata": {
                              "speaker": "Joe"
                            }
                          },
                          {
                            "text": "Hi, Joe! <short pause> How are you?",
                            "speech_metadata": {
                              "speaker": "Jane",
                              "style": "warm and friendly"
                            }
                          }
                        ]
                      }
                    ],
                    "generationConfig": {
                      "responseModalities": [
                        "AUDIO"
                      ],
                      "speechConfig": {
                        "multiSpeakerVoiceConfig": {
                          "speakerVoiceConfigs": [
                            {
                              "speaker": "Joe",
                              "voiceConfig": {
                                "voice": "Puck"
                              }
                            },
                            {
                              "speaker": "Jane",
                              "voiceConfig": {
                                "voice": "Kore"
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "非流式响应为完整音频：inlineData.mimeType 通常为 audio/wav，data 为带 RIFF 头的完整 WAV 的 Base64 编码，解码后可直接保存为 .wav 文件。\n流式请求返回 text/event-stream，每个 data 都是本结构的 JSON 分片；音频分片为无头的原始 PCM（24 kHz、单声道、16 位有符号小端），需逐块 Base64 解码后拼接字节。\n以下短 Base64 仅为结构示意，不是可播放的完整音频。",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerateContentResponse"
                },
                "examples": {
                  "audio": {
                    "summary": "以下短 Base64 仅为结构示意，不是可播放的完整音频。",
                    "value": {
                      "candidates": [
                        {
                          "content": {
                            "role": "model",
                            "parts": [
                              {
                                "inlineData": {
                                  "mimeType": "audio/wav",
                                  "data": "AAAAAA=="
                                }
                              }
                            ]
                          },
                          "finishReason": "STOP"
                        }
                      ],
                      "usageMetadata": {
                        "promptTokenCount": 12,
                        "candidatesTokenCount": 20,
                        "totalTokenCount": 32
                      }
                    }
                  }
                }
              }
            }
          },
          "default": {
            "description": "错误响应。",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "error": {
                    "code": 400,
                    "message": "Invalid request",
                    "status": "INVALID_ARGUMENT"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "geminiApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "x-goog-api-key",
        "description": "填写 Modelverse API key。"
      }
    },
    "schemas": {
      "GenerateContentRequest": {
        "type": "object",
        "description": "TTS 请求体。待朗读文本放入 contents，并通过 generationConfig 指定输出音频与音色。",
        "properties": {
          "contents": {
            "type": "array",
            "minItems": 1,
            "description": "输入内容数组。TTS 仅接受纯文本输入，通常只传一个 role=user 的内容项，其 parts 会按顺序合成为连续音频。",
            "items": {
              "$ref": "#/components/schemas/RequestContent"
            }
          },
          "generationConfig": {
            "description": "生成配置。必须声明输出模态为 AUDIO，并指定单人或多人的音色配置。",
            "$ref": "#/components/schemas/GenerationConfig"
          }
        },
        "required": [
          "contents",
          "generationConfig"
        ]
      },
      "RequestContent": {
        "type": "object",
        "description": "单个对话内容项。",
        "properties": {
          "role": {
            "type": "string",
            "const": "user",
            "description": "内容角色，TTS 固定为 user。"
          },
          "parts": {
            "type": "array",
            "minItems": 1,
            "description": "文本片段列表，按顺序合成。每个 part 视为一个回合（turn），其 speech_metadata.style 作用于该片段整体；多人语音时每个 part 代表一位说话人的一句台词。",
            "items": {
              "$ref": "#/components/schemas/RequestPart"
            }
          }
        },
        "required": [
          "role",
          "parts"
        ]
      },
      "RequestPart": {
        "type": "object",
        "description": "一个待朗读的文本片段及其语音元数据。",
        "properties": {
          "text": {
            "type": "string",
            "description": "逐字朗读的文本，模型严格按字面内容朗读。情绪、语速等风格要求不要写在这里，应放入 speech_metadata.style。瞬时非语音事件可用尖括号内联标签插入，例如 `Wait... <short pause> did you hear that? <sigh>` 或 `Excuse me <cough> as I was saying...`。"
          },
          "speech_metadata": {
            "description": "回合级语音元数据，控制该片段的朗读风格；多人语音时还需指定说话人。",
            "$ref": "#/components/schemas/SpeechMetadata"
          }
        },
        "required": [
          "text"
        ]
      },
      "SpeechMetadata": {
        "type": "object",
        "description": "文本片段（回合）级别的语音控制元数据。",
        "properties": {
          "style": {
            "type": "string",
            "description": "回合级风格指令，作用于整个片段的情绪、表达方式、韵律、节奏和音量，使用自然语言描述，例如 `cheerful and friendly`、`whispered urgently`、`out of breath`、`warm and enthusiastic`。"
          },
          "speaker": {
            "type": "string",
            "description": "多人语音时该片段的说话人标识，取值必须与 generationConfig.speechConfig.multiSpeakerVoiceConfig.speakerVoiceConfigs[].speaker 完全一致；单人语音无需设置。"
          }
        }
      },
      "GenerationConfig": {
        "type": "object",
        "description": "生成配置。",
        "properties": {
          "responseModalities": {
            "type": "array",
            "description": "响应模态。TTS 模型仅返回音频，固定设为 [\"AUDIO\"]。",
            "items": {
              "type": "string",
              "const": "AUDIO"
            },
            "minItems": 1,
            "maxItems": 1
          },
          "speechConfig": {
            "description": "音色配置。单人与多人二选一：单人使用 voiceConfig，多人使用 multiSpeakerVoiceConfig。",
            "$ref": "#/components/schemas/SpeechConfig"
          }
        },
        "required": [
          "responseModalities",
          "speechConfig"
        ]
      },
      "SpeechConfig": {
        "type": "object",
        "description": "音色配置。voiceConfig 与 multiSpeakerVoiceConfig 必须且只能设置一个：单人朗读使用 voiceConfig，双人或多人的对话使用 multiSpeakerVoiceConfig。",
        "properties": {
          "voiceConfig": {
            "description": "单人朗读的音色配置。",
            "$ref": "#/components/schemas/SingleVoiceConfig"
          },
          "multiSpeakerVoiceConfig": {
            "description": "多人对话中各说话人的音色配置。",
            "$ref": "#/components/schemas/MultiSpeakerVoiceConfig"
          }
        },
        "oneOf": [
          {
            "required": [
              "voiceConfig"
            ],
            "not": {
              "required": [
                "multiSpeakerVoiceConfig"
              ]
            }
          },
          {
            "required": [
              "multiSpeakerVoiceConfig"
            ],
            "not": {
              "required": [
                "voiceConfig"
              ]
            }
          }
        ]
      },
      "SingleVoiceConfig": {
        "type": "object",
        "description": "单人与多人朗读的音色。",
        "properties": {
          "voice": {
            "type": "string",
            "description": "音色名称或音色 ID，例如预置音色 `Kore`、`Puck`。官方提供 30 个预置音色，也支持扩展音色库 ID 及自定义音色（`voice_...` / `voicekey_...`）；平台实际可用的音色范围以控制台为准。以下为 30 个预置音色及其特征：Achernar（柔和）、Achird（友好）、Algenib（沙哑）、Algieba（平滑）、Alnilam（坚定）、Aoede（轻快）、Autonoe（清亮）、Callirrhoe（舒缓自在）、Charon（充实）、Despina（流畅）、Enceladus（气声）、Erinome（清晰）、Fenrir（激昂）、Gacrux（成熟）、Iapetus（清晰）、Kore（坚定）、Laomedeia（欢快）、Leda（青春洋溢）、Orus（坚定）、Puck（欢快）、Pulcherrima（直率）、Rasalgethi（充实）、Sadachbia（活泼）、Sadaltager（博学）、Schedar（均匀）、Sulafat（温暖）、Umbriel（随和）、Vindemiatrix（轻柔）、Zephyr（明快）、Zubenelgenubi（随性）。",
            "examples": [
              "Achernar",
              "Achird",
              "Algenib",
              "Algieba",
              "Alnilam",
              "Aoede",
              "Autonoe",
              "Callirrhoe",
              "Charon",
              "Despina",
              "Enceladus",
              "Erinome",
              "Fenrir",
              "Gacrux",
              "Iapetus",
              "Kore",
              "Laomedeia",
              "Leda",
              "Orus",
              "Puck",
              "Pulcherrima",
              "Rasalgethi",
              "Sadachbia",
              "Sadaltager",
              "Schedar",
              "Sulafat",
              "Umbriel",
              "Vindemiatrix",
              "Zephyr",
              "Zubenelgenubi"
            ]
          }
        },
        "required": [
          "voice"
        ]
      },
      "MultiSpeakerVoiceConfig": {
        "type": "object",
        "description": "多人对话的音色配置。",
        "properties": {
          "speakerVoiceConfigs": {
            "type": "array",
            "minItems": 1,
            "description": "说话人与音色的映射列表，每位说话人一项，双人对话需配置两项。speaker 为自定义标识，用于与 parts[].speech_metadata.speaker 对应。",
            "items": {
              "$ref": "#/components/schemas/SpeakerVoiceConfig"
            }
          }
        },
        "required": [
          "speakerVoiceConfigs"
        ]
      },
      "SpeakerVoiceConfig": {
        "type": "object",
        "description": "单个说话人的音色配置。",
        "properties": {
          "speaker": {
            "type": "string",
            "description": "说话人标识，需与 parts[].speech_metadata.speaker 一致，可自定义命名，例如 Joe、Jane。"
          },
          "voiceConfig": {
            "description": "该说话人使用的音色，结构与单人朗读的 voiceConfig 相同。",
            "$ref": "#/components/schemas/SingleVoiceConfig"
          }
        },
        "required": [
          "speaker",
          "voiceConfig"
        ]
      },
      "GenerateContentResponse": {
        "type": "object",
        "description": "TTS 响应。非流式返回完整音频；流式（SSE）下每个事件的 data 都是该结构的 JSON 分片。",
        "properties": {
          "candidates": {
            "type": "array",
            "description": "候选结果列表。",
            "items": {
              "$ref": "#/components/schemas/Candidate"
            }
          },
          "usageMetadata": {
            "description": "token 用量统计。",
            "$ref": "#/components/schemas/UsageMetadata"
          },
          "modelVersion": {
            "type": "string",
            "description": "实际使用的模型版本。"
          },
          "responseId": {
            "type": "string",
            "description": "本次响应的唯一标识。"
          }
        },
        "additionalProperties": true
      },
      "Candidate": {
        "type": "object",
        "description": "单个候选结果。",
        "properties": {
          "content": {
            "description": "模型返回的内容，音频位于 parts[].inlineData。",
            "$ref": "#/components/schemas/ResponseContent"
          },
          "finishReason": {
            "type": "string",
            "description": "完成原因。正常结束为 STOP；不限定其他可能取值。"
          },
          "index": {
            "type": "integer",
            "description": "候选序号，从 0 开始。"
          }
        },
        "additionalProperties": true
      },
      "ResponseContent": {
        "type": "object",
        "description": "响应内容。",
        "properties": {
          "role": {
            "type": "string",
            "description": "内容角色，通常为 model。"
          },
          "parts": {
            "type": "array",
            "description": "内容片段列表，音频数据位于 inlineData。",
            "items": {
              "$ref": "#/components/schemas/ResponsePart"
            }
          }
        },
        "additionalProperties": true
      },
      "ResponsePart": {
        "type": "object",
        "description": "响应片段。",
        "properties": {
          "inlineData": {
            "description": "内联音频数据。",
            "$ref": "#/components/schemas/InlineData"
          },
          "text": {
            "type": "string",
            "description": "文本内容，TTS 通常为空。"
          }
        },
        "additionalProperties": true
      },
      "InlineData": {
        "type": "object",
        "description": "内联音频数据。",
        "properties": {
          "mimeType": {
            "type": "string",
            "description": "音频媒体类型。非流式返回带 RIFF 头的完整 WAV（`audio/wav`，16 位 PCM、24 kHz、单声道）；流式返回无标头原始 16 位有符号小端 PCM（`audio/l16; rate=24000; channels=1`，24 kHz、单声道）。请按实际返回值处理，不要假定固定类型。"
          },
          "data": {
            "type": "string",
            "contentEncoding": "base64",
            "description": "Base64 编码的音频字节。流式场景需逐块 Base64 解码后按顺序拼接字节，再按需添加 WAV 头；不要直接拼接 Base64 字符串。"
          }
        },
        "additionalProperties": true,
        "required": [
          "mimeType",
          "data"
        ]
      },
      "UsageMetadata": {
        "type": "object",
        "description": "token 用量。",
        "properties": {
          "promptTokenCount": {
            "type": "integer",
            "description": "输入（文本）token 数。"
          },
          "candidatesTokenCount": {
            "type": "integer",
            "description": "输出（音频）token 数。"
          },
          "totalTokenCount": {
            "type": "integer",
            "description": "总 token 数。"
          }
        },
        "additionalProperties": true
      },
      "ErrorResponse": {
        "type": "object",
        "description": "错误响应。",
        "properties": {
          "error": {
            "description": "错误详情。",
            "$ref": "#/components/schemas/Error"
          }
        },
        "additionalProperties": true,
        "required": [
          "error"
        ]
      },
      "Error": {
        "type": "object",
        "description": "标准 Google API 错误结构。",
        "properties": {
          "code": {
            "type": "integer",
            "description": "HTTP 状态码，例如 400。"
          },
          "message": {
            "type": "string",
            "description": "可读的错误信息。"
          },
          "status": {
            "type": "string",
            "description": "规范错误状态，例如 INVALID_ARGUMENT、PERMISSION_DENIED、RESOURCE_EXHAUSTED。"
          },
          "details": {
            "type": "array",
            "description": "用于定位问题的附加错误详情。",
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          }
        },
        "additionalProperties": true
      }
    }
  }
}
```
