语音合成 Sambert Python SDK - 千问云
跳转到主要内容
Sambert

语音合成 Sambert Python SDK

本文介绍语音合成 Sambert Python SDK 的参数和接口细节。

前提条件

快速开始

非流式调用

不传入 callback 参数时,call 函数将在语音合成完成后返回所有语音合成结果。
# coding=utf-8
import sys
from dashscope.audio.tts import SpeechSynthesizer

result = SpeechSynthesizer.call(model='sambert-zhichu-v1',
                                text='今天天气怎么样',
                                sample_rate=48000,
                                format='wav')
if result.get_audio_data() is not None:
  with open('output.wav', 'wb') as f:
    f.write(result.get_audio_data())
  print('SUCCESS: get audio data: %dbytes in output.wav' %
        (sys.getsizeof(result.get_audio_data())))
else:
  print('ERROR: response is %s' % (result.get_response()))

单向流式调用

传入 callback 参数时,在语音合成过程中,服务器将回调 callback 中对应函数,流式返回语音合成结果。
# coding=utf-8
import sys
from dashscope.api_entities.dashscope_response import SpeechSynthesisResponse
from dashscope.audio.tts import ResultCallback, SpeechSynthesizer, SpeechSynthesisResult

class Callback(ResultCallback):
  def on_open(self):
    print('Speech synthesizer is opened.')

  def on_complete(self):
    print('Speech synthesizer is completed.')

  def on_error(self, response: SpeechSynthesisResponse):
    print('Speech synthesizer failed, response is %s' % (str(response)))

  def on_close(self):
    print('Speech synthesizer is closed.')

  def on_event(self, result: SpeechSynthesisResult):
    if result.get_audio_frame() is not None:
      print('audio result length:', sys.getsizeof(result.get_audio_frame()))
    if result.get_timestamp() is not None:
      print('timestamp result:', str(result.get_timestamp()))

callback = Callback()
SpeechSynthesizer.call(model='sambert-zhichu-v1',
                       text='今天天气怎么样',
                       sample_rate=48000,
                       callback=callback,
                       word_timestamp_enabled=True,
                       phoneme_timestamp_enabled=True)

请求参数

参数类型默认值是否必须说明
modelstr-模型名,参见模型列表
textstr-待合成文本。
formatstrwav音频格式,支持 wavmp3pcm 等。
sample_rateint16000音频采样率(Hz)。
volumeint50音量,取值范围 0~100。
ratefloat1.0语速,取值范围 0.5~2.0。
pitchfloat1.0语调,取值范围 0.5~2.0。
word_timestamp_enabledboolFalse是否开启字级别时间戳。
phoneme_timestamp_enabledboolFalse是否开启音素级别时间戳。
callbackResultCallback-回调接口,传入后启用单向流式调用模式。

关键接口

SpeechSynthesizer 类

SpeechSynthesizer 可以通过 from dashscope.audio.tts import SpeechSynthesizer 方式引入。其关键接口如下:
接口/方法参数返回值描述
@classmethod
def call(cls, model: str, text: str, callback: ResultCallback = None, workspace: str = None, **kwargs) -> SpeechSynthesisResult:
model:模型名,参见模型列表
text:待合成文本
callback:回调接口(ResultCallback)
workspace:DashScope workspace id
kwargs:请求参数,如 format
合成结果 SpeechSynthesisResult,非流式调用时需要处理该返回,流式调用时不必处理开启语音合成任务。根据是否传入参数 callback,有如下两种情况:不传入 callback 参数时,call 函数将在语音合成完成后返回所有结果;传入 callback 参数时,服务器将回调 callback 中对应函数,流式返回合成结果。

回调接口(ResultCallback)

单向流式调用时,服务端会通过回调的方式将关键流程信息和数据返回给客户端。您需要实现回调方法,处理服务端返回的信息或者数据。
class Callback(ResultCallback):
  def on_open(self):
    print('和服务器成功建立连接')

  def on_complete(self):
    print('任务完成')

  def on_error(self, response: SpeechSynthesisResponse):
    print('报错:%s' % (str(response)))

  def on_close(self):
    print('和服务器之间的连接已关闭')

  def on_event(self, result: SpeechSynthesisResult):
    if result.get_audio_frame() is not None:
      print('收到二进制音频数据:', result.get_audio_frame())
    if result.get_timestamp() is not None:
      print('收到时间戳数据:', str(result.get_timestamp()))

callback = Callback()
接口/方法参数返回值描述
def on_open(self) -> None当和服务建立连接完成后立刻被回调。
def on_event(self, result: SpeechSynthesisResult) -> Noneresult:音频数据和时间戳信息(SpeechSynthesisResult)当服务端返回合成数据时被回调。
def on_complete(self) -> None当所有合成数据全部返回后被回调。
def on_error(self, response: SpeechSynthesisResponse)response:异常信息当调用过程出现异常以及服务返回错误后被回调。
def on_close(self) -> None服务关闭连接后被回调。

响应结果

音频数据和时间戳信息(SpeechSynthesisResult)

SpeechSynthesisResult 封装了语音合成结果,常用的接口为 get_audio_frameget_timestampget_audio_dataget_timestamps
接口/方法参数返回值描述
def get_audio_frame(self) -> bytes当前合成的二进制音频数据片段流式合成中,获取当前合成的音频帧数据。
该函数要在流式合成时,在回调方法 on_event 中使用。
def get_timestamp(self) -> Dict[str, str]当前合成的句子对应的时间戳信息流式合成中,获取当前合成的句子对应的时间戳信息。
该函数要在流式合成时,在回调方法 on_event 中使用。
def get_audio_data(self) -> bytes完整的二进制音频数据获取完整的二进制音频数据。
def get_timestamps(self) -> List[Dict[str, str]]所有句子对应的时间戳信息获取所有句子对应的时间戳信息。

时间戳信息

get_timestamp 函数获取当前合成句子的时间戳信息,get_timestamps 函数获取所有句子的时间戳信息。 单个句子的时间戳信息示例如下,其中 words 对应字级别时间戳信息,phonemes 对应音素级别时间戳信息:
{
  "begin_time": 0,
  "end_time": 1412,
  "words": [
    {
      "text": "今",
      "begin_time": 0,
      "end_time": 200,
      "phonemes": [
        {"begin_time": 0, "end_time": 82, "text": "j_c", "tone": 1},
        {"begin_time": 82, "end_time": 200, "text": "in_c", "tone": 1}
      ]
    }
  ]
}
各参数含义如下:
参数类型说明
begin_timeint句子、字、音素开始时间,单位为 ms。
end_timeint句子、字、音素结束时间,单位为 ms。
wordslist字级别时间戳信息,需要请求中 word_timestamp_enabled 也设置为 true
textstr文本信息。
phonemeslist音素级别时间戳信息,需要请求中 phoneme_timestamp_enabled 也设置为 true
tonestr音调。英文中,0、1、2 分别代表轻音、重音和次重音。拼音中,1、2、3、4、5 分别代表一声、二声、三声、四声和轻声。

错误码

在使用 API 过程中,如果调用失败并返回错误信息,请参见错误信息进行解决。

更多示例

更多示例,请参见 GitHub

常见问题

请参见 GitHub QA

模型列表

音色model 参数时间戳支持适用场景特色语言默认采样率(Hz)
知楠sambert-zhinan-v1通用场景广告男声中文+英文48k
知琪sambert-zhiqi-v1通用场景温柔女声中文+英文48k
知厨sambert-zhichu-v1新闻播报舌尖男声中文+英文48k
知德sambert-zhide-v1新闻播报新闻男声中文+英文48k
知佳sambert-zhijia-v1新闻播报标准女声中文+英文48k
知茹sambert-zhiru-v1新闻播报新闻女声中文+英文48k
知倩sambert-zhiqian-v1配音解说、新闻播报资讯女声中文+英文48k
知祥sambert-zhixiang-v1配音解说磁性男声中文+英文48k
知薇sambert-zhiwei-v1阅读产品简介萝莉女声中文+英文48k
知浩sambert-zhihao-v1通用场景咨询男声中文+英文16k
知婧sambert-zhijing-v1通用场景严厉女声中文+英文16k
知茗sambert-zhiming-v1通用场景诙谐男声中文+英文16k
知墨sambert-zhimo-v1通用场景情感男声中文+英文16k
知娜sambert-zhina-v1通用场景浙普女声中文+英文16k
知树sambert-zhishu-v1通用场景资讯男声中文+英文16k
知莎sambert-zhistella-v1通用场景知性女声中文+英文16k
知婷sambert-zhiting-v1通用场景电台女声中文+英文16k
知笑sambert-zhixiao-v1通用场景资讯女声中文+英文16k
知雅sambert-zhiya-v1通用场景严厉女声中文+英文16k
知晔sambert-zhiye-v1通用场景青年男声中文+英文16k
知颖sambert-zhiying-v1通用场景软萌童声中文+英文16k
知媛sambert-zhiyuan-v1通用场景知心姐姐中文+英文16k
知悦sambert-zhiyue-v1客服温柔女声中文+英文16k
知柜sambert-zhigui-v1阅读产品简介直播女声中文+英文16k
知硕sambert-zhishuo-v1数字人自然男声中文+英文16k
知妙(多情感)sambert-zhimiao-emo-v1阅读产品简介、数字人、直播多种情感女声中文+英文16k
知猫sambert-zhimao-v1阅读产品简介、配音解说、数字人、直播直播女声中文+英文16k
知伦sambert-zhilun-v1配音解说悬疑解说中文+英文16k
知飞sambert-zhifei-v1配音解说激昂解说中文+英文16k
知达sambert-zhida-v1新闻播报标准男声中文+英文16k
Camilasambert-camila-v1通用场景西班牙语女声西班牙语16k
Perlasambert-perla-v1通用场景意大利语女声意大利语16k
Indahsambert-indah-v1通用场景印尼语女声印尼语16k
Clarasambert-clara-v1通用场景法语女声法语16k
Hannasambert-hanna-v1通用场景德语女声德语16k
Bethsambert-beth-v1通用场景咨询女声美式英文16k
Bettysambert-betty-v1通用场景客服女声美式英文16k
Callysambert-cally-v1通用场景自然女声美式英文16k
Cindysambert-cindy-v1通用场景对话女声美式英文16k
Evasambert-eva-v1通用场景陪伴女声美式英文16k
Donnasambert-donna-v1通用场景教育女声美式英文16k
Briansambert-brian-v1通用场景客服男声美式英文16k
Waansambert-waan-v1通用场景泰语女声泰语16k
定制热词
专项模型 API

通过Java SDK管理定制热词列表,包括创建、查询、更新和删除热词列表。

  • 通过Java SDK管理定制热词列表,包括VocabularyService类的方法说明与示例代码。 用户指南:用户指南

    服务端点

    语音合成
    https://dashscope.aliyuncs.com/api/v1
    

    VocabularyService

    包路径com.alibaba.dashscope.audio.asr.vocabulary.VocabularyService 功能:管理热词列表的生命周期(创建、查询、更新、删除)

    构造方法

    public VocabularyService(String apiKey)
    
    参数
    参数类型说明
    apiKeyStringDashScope API Key

    createVocabulary() - 创建热词列表

    方法签名
    public Vocabulary createVocabulary(String targetModel,String prefix,JsonArray vocabulary) throws NoApiKeyException, 高并发最佳实践
  • InputRequiredException
    参数
    参数类型必填说明
    targetModelString使用热词列表的语音识别模型,必须与后续调用语音识别接口时使用的模型一致。
    prefixString热词列表自定义前缀,仅允许数字和小写字母,长度不超过10个字符。
    vocabularyJsonArray热词列表,每个JsonObject包含 text、weight、lang 等字段。详情请参见热词对象结构
    返回值
    类型说明
    Vocabulary热词列表对象,包含 vocabularyId 等信息。
    异常
    异常类型说明
    NoApiKeyExceptionAPI Key 为空。
    InputRequiredException必填参数为空。

    listVocabulary() - 批量查询热词列表

    方法签名
    语音识别
    public Vocabulary[] listVocabulary(String prefix) throws NoApiKeyException, InputRequiredException
    
    public Vocabulary[] listVocabulary(String prefix, int pageIndex, int pageSize) throws NoApiKeyException, InputRequiredException
    
    参数
    参数类型必填说明
    String热词列表自定义前缀,如果设定则只返回指定前缀的热词列表。
    pageIndexint页码索引,从0开始计数。默认值:0。
    pageSizeint每页包含数据条数。默认值:10。
    返回值
    类型说明
    Vocabulary[]热词列表对象数组。
    Vocabulary 对象字段(list返回)
    字段类型说明
    vocabularyIdString热词列表ID。
    gmtCreateString创建时间。
    gmtModifiedString修改时间。
    statusString状态:OK(可调用)、UNDEPLOYED(不可调用)。
    异常
    异常类型说明
    NoApiKeyExceptionAPI Key 为空。
    InputRequiredException必填参数为空。

    queryVocabulary() - 查询热词列表

    方法签名
    public Vocabulary queryVocabulary(String vocabularyId) throws NoApiKeyException, InputRequiredException
    
    参数
    参数类型必填说明
    vocabularyIdString需要查询的热词列表ID。
    返回值
    类型说明
    Vocabulary热词列表对象,包含详细信息。
    Vocabulary 对象字段(query返回)
    音乐生成
    图片翻译
    字段类型说明
    vocabularyJsonArray热词列表内容
    targetModelString使用热词列表的语音识别模型,必须与后续调用语音识别接口时使用的模型一致。
    gmtCreateString创建时间。
    gmtModifiedString修改时间。
    statusString状态:OK(可调用)、UNDEPLOYED(不可调用)。
    异常
    异常类型说明
    NoApiKeyExceptionAPI Key 为空。
    InputRequiredException必填参数为空。

    updateVocabulary() - 更新热词列表

    方法签名 参数
    参数类型必填说明
    vocabularyIdString需要更新的热词列表ID。
    vocabularyJsonArray新的热词列表,将完全替换原有内容。
    返回值:无 异常
    异常类型说明
    NoApiKeyExceptionAPI Key 为空。
    InputRequiredException必填参数为空。

    多模态向量
    deleteVocabulary() - 删除热词列表

    方法签名
    public void deleteVocabulary(String vocabularyId) throws NoApiKeyException, InputRequiredException
    
    参数
    参数类型必填说明
    vocabularyIdString需要删除的热词列表ID。
    返回值:无 异常
    重排序
    平台 API
    • 异常类型说明
      NoApiKeyExceptionAPI Key 为空。
      InputRequiredException必填参数为空。

    Vocabulary 类

    包路径com.alibaba.dashscope.audio.asr.vocabulary.Vocabulary 功能:热词列表对象,封装热词列表的元数据和内容

    主要方法

    方法返回类型说明
    getVocabularyId()String获取热词列表ID。
    getTargetModel()String获取目标模型。
    getVocabulary()JsonArray获取热词列表内容。
    getStatus()String获取状态。
    getGmtCreate()String获取创建时间。
    getGmtModified()String获取修改时间。
    getData()JsonObject获取完整数据(JSON格式)。

  • 热词对象结构

    用于 vocabulary 参数的 JsonObject 定义
    字段类型必填说明
    textString热词文本。热词文本的语言必须在所选模型的支持范围内,不同模型支持的语言各不相同。热词用于提升识别的准确率,请使用实际词语而非任意字符组合。长度限制:含非 ASCII 字符时不超过 15 个字符;纯 ASCII 时空格分隔片段不超过 7 个。
    weightint热词权重。常用值:4。取值范围:[1, 5]。如果效果不明显,可以适当增加权重,但权重过大可能产生负面效果,导致其他词语识别不准确。
    langString待识别音频的语言代码。设置后,系统将对指定语种进行热词识别增强。如果无法提前确定语种,可不设置,模型会自动识别语种。取值范围(因模型而异):Paraformer 支持 zh(中文)、en(英文)、ja(日语)、yue(粤语)、ko(韩语)、de(德语)、fr(法语)、ru(俄语);Fun-ASR 支持 zh(中文)、en(英文)、ja(日语)。

    示例代码

    工具包与框架
    创建热词列表

    ,\"developer-guides/clients-and-developer-tools/cherry-studio\",\"developer-guides/clients-and-developer-tools/chatbox\",\"developer-guides/clients-and-developer-tools/cline\",\"developer-guides/clients-and-developer-tools/qoder\",\"developer-guides/clients-and-developer-tools/lingma\",\"developer-guides/clients-and-developer-tools/kilo-cli\",\"developer-guides/clients-and-developer-tools/postman\",\"developer-guides/clients-and-developer-tools/dify\",\"developer-guides/clients-and-developer-tools/other-tools\"]},\"developer-guides/integrations/mlops-observability\"]},{\"group\":\"模型生产\",\"icon\":\"ModelOutlined\",\"pages\":[{\"group\":\"数据集\",\"pages\":[\"developer-guides/datasets/overview\",\"developer-guides/datasets/create-dataset\",\"developer-guides/datasets/manage-datasets\"]},{\"group\":\"微调\",\"pages\":[\"developer-guides/fine-tuning/overview\",\"developer-guides/fine-tuning/create-fine-tuning-job\",\"developer-guides/fine-tuning/manage-fine-tuning-jobs\",\"developer-guides/fine-tuning/hyperparameters\"]},{\"group\":\"部署\",\"pages\":[\"developer-guides/deployment/overview\",\"developer-guides/deployment/manage-deployments\",\"developer-guides/custom-models/overview\"]}]},{\"group\":\"安全与合规\",\"icon\":\"ShieldCodeOutlined\",\"pages\":[\"developer-guides/security-compliance/data-security\",\"developer-guides/security-compliance/zero-data-retention\",\"developer-guides/security-compliance/audit-logs\"]}]},{\"tab\":\"API 与 SDK 参考\",\"groups\":[{\"group\":\"使用 API\",\"icon\":\"SettingsCodeOutlined\",\"pages\":[\"api-reference/preparation/api-key\",\"api-reference/preparation/export-api-key-env\",\"api-reference/preparation/install-sdk\"]},{\"group\":\"对话模型\",\"icon\":\"MessageChatbotOutlined\",\"pages\":[\"api-reference/chat/openai-chat\",{\"group\":\"OpenAI Responses\",\"pages\":[\"api-reference/chat/openai-responses\",\"api-reference/chat/retrieve-response\",\"api-reference/chat/delete-response\",\"api-reference/chat/list-input-items\"]},\"api-reference/chat/anthropic\",\"api-reference/chat/dashscope\"]},{\"group\":\"图像生成 API\",\"icon\":\"PhotoCodeOutlined\",\"pages\":[{\"group\":\"文生图\",\"pages\":[{\"group\":\"千问\",\"pages\":[\"api-reference/image-generation/qwen-text-to-image\",\"api-reference/image-generation/qwen-text-to-image-async\",\"api-reference/image-generation/qwen-text-to-image-task-query\"]},\"api-reference/image-generation/z-image\",{\"group\":\"万相V2\",\"pages\":[\"api-reference/image-generation/wan-text-to-image-v2/synchronous\",\"api-reference/image-generation/wan-text-to-image-v2/create-task\",\"api-reference/image-generation/wan-text-to-image-v2/query-result\"]},{\"group\":\"万相V1\",\"pages\":[\"api-reference/image-generation/wanx-v1-text-to-image/create-task\",\"api-reference/image-generation/wanx-v1-text-to-image/query-result\"]}]},{\"group\":\"图像编辑\",\"pages\":[\"api-reference/image-generation/qwen-image-editing\",{\"group\":\"万相2.7\",\"pages\":[\"api-reference/image-generation/wan27-image-gen-edit/synchronous\",\"api-reference/image-generation/wan27-image-gen-edit/create-task\",\"api-reference/image-generation/wan27-image-gen-edit/query-result\"]},{\"group\":\"万相2.6\",\"pages\":[\"api-reference/image-generation/wan26-image-gen-edit/synchronous\",\"api-reference/image-generation/wan26-image-gen-edit/create-task\",\"api-reference/image-generation/wan26-image-gen-edit/query-result\"]},{\"group\":\"万相2.5\",\"pages\":[\"api-reference/image-generation/wan25-general-image-editing/create-task\",\"api-reference/image-generation/wan25-general-image-editing/query-result\"]},{\"group\":\"万相2.1\",\"pages\":[\"api-reference/image-generation/wan21-general-image-editing/create-task\",\"api-reference/image-generation/wan21-general-image-editing/query-result\"]}]},{\"group\":\"涂鸦作画\",\"pages\":[\"api-reference/image-generation/wanx-sketch-to-image/create-task\",\"api-reference/image-generation/wanx-sketch-to-image/query-result\"]},{\"group\":\"图像局部重绘\",\"pages\":[\"api-reference/image-generatio