> For the complete documentation index, see [llms.txt](https://iruca.gitbook.io/ope.ai-pod/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://iruca.gitbook.io/ope.ai-pod/features/text-to-speech-wen-ben-zhuan-yu-yin-gong-neng.md).

# Text to speech文本转语音功能

```python
from pathlib import Path
from openai import OpenAI

apiKey  = "KEY"
baseURL = "https://testpod.ope.ai/v1"

client = OpenAI(api_key=apiKey, base_url=baseURL)

speech_file_path = Path(__name__).parent / "speech.mp3"
response = client.audio.speech.create(
  model="CosyVoice-300M-SFT",
  voice="粤语女",
  input="如果佢去我就去 如果唔使钱我就要 如果落雨就唔去 如果得闲就嚟"
)

response.stream_to_file(speech_file_path)
```

1. 构建文件路径

`Path(__name__).parent` 获取当前脚本所在的目录，`/ "speech.mp3"` 则将该路径与文件名 `speech.mp3` 连接，最终得到了生成语音文件保存的路径。

2. 生成语音请求

`client.audio.speech.create` 这行是调用 API 生成语音请求的部分，同文本生成部分的类似代码。`model`是使用的语音模型`Voice` 可以有如下的选择：

```python
  voice="中文女",
  voice="中文男",
  voice="日语男",
  voice="粤语女",
  voice="英文女",
  voice="英文男",
  voice="韩语女",
```

`input`是用来生成语音的文本内容。

3. 语音写入

`stream_to_file(speech_file_path)` 表示将生成的音频流保存到指定的文件路径（`speech.mp3`）中。<br>

curl 调用的例子：

```python
curl https://testpod.ope.ai/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "CosyVoice-300M-SFT",
    "input": "如果佢去我就去 如果唔使钱我就要 如果落雨就唔去 如果得闲就嚟",
    "voice": "粤语女"
  }' \
  --output speech.mp3
```
