Python SDK

本文介绍如何使用阿里云智能语音服务提供的Python SDK,包括SDK的安装方法及SDK代码示例。

前提条件

下载安装

  1. 下载Python SDK。

Github获取Python SDK,或直接下载streamInputTts-github-python

  1. 安装SDK依赖。

进入SDK根目录使用如下命令安装SDK依赖:

python -m pip install -r requirements.txt
  1. 安装SDK。

依赖安装完成后使用如下命令安装SDK:

python -m pip install .
  1. 安装完成后通过以下代码导入SDK。

# -*- coding: utf-8 -*-
import nls
重要

上述命令均需要在SDK根目录中执行。

关键接口

startStreamInputTts:与服务端进行websocket建连操作,并完成回调、参数设置等操作

  • """
    开始语音转写:发送语音转写请求,同步接收服务端确认
    
    Parameters:
    -----------
    voice: str
        voice for text-to-speech, default is xiaoyun
    aformat: str
        audio binary format, support: 'pcm', 'wav', 'mp3', default is 'pcm'
    sample_rate: int
        audio sample rate, default is 24000, support:8000, 11025, 16000, 22050,
        24000, 32000, 44100, 48000
    volume: int
        audio volume, from 0~100, default is 50
    speech_rate: int
        speech rate from -500~500, default is 0
    pitch_rate: int
        pitch for voice from -500~500, default is 0
    ex: dict
        dict which will merge into 'payload' field in request
    """
    def startStreamInputTts(
        self,
        voice="longxiaochun",
        aformat="pcm",
        sample_rate=24000,
        volume=50,
        speech_rate=0,
        pitch_rate=0,
    )
  • sendStreamInputTts:以流式的方式发送文本

    """
    以流式的方式发送文本
    Parameters:
    -----------
    text: str
        utf-8 text
    """
    def sendStreamInputTts(self, text)
  • stopStreamInputTts:以阻塞的方式停止流式文本语音合成,并与服务端断开websocket连接

    """
    停止合成任务,等待收到剩余合成结果后返回
    """
    def stopStreamInputTts(self)

    回调函数说明

    Python回调函数在创建对象时作为参数配置,说明见下表:

    参数

    参数说明

    on_data

    当存在合成数据后的回调参数。回调参数包含以下两个:

    • 对应start方法中aformat的二进制音频数据

    • 用户自定义参数

    其中,用户自定义参数为下方callback_args字段中返回的参数内容。

    on_sentence_begin

    收到SentenceBegin事件时回调。回调参数包含以下两个

    • JSON形式的字符串

    • 用户自定义参数

    其中,用户自定义参数为下方callback_args字段中返回的参数内容。

    on_sentence_synthesis

    时间戳预留接口。CosyVoice目前不支持时间戳功能,不需处理。

    on_sentence_end

    时间戳预留接口,CosyVoice目前不支持时间戳功能,不需处理。

    on_complete

    时间戳预留接口,CosyVoice目前不支持时间戳功能,不需处理。

    on_error

    SDK或云端出现错误时的回调参数。回调参数包含以下两个:

    • JSON形式的字符串

    • 用户自定义参数

    其中,用户自定义参数为下方callback_args字段中返回的参数内容。

    on_close

    当和云端连接断开时的回调参数。回调参数为用户自定义参数,即用户自定义参数为下方callback_args字段中返回的参数内容。

调用示例

以下Python代码示例模拟了流式文本输入,请求语音合成并保存到本地的全过程。

重要

代码运行前需要替换 your-appkey 以及 your-token

# coding=utf-8
#
# Installation instructions for pyaudio:
# APPLE Mac OS X
#   brew install portaudio
#   pip install pyaudio
# Debian/Ubuntu
#   sudo apt-get install python-pyaudio python3-pyaudio
#   or
#   pip install pyaudio
# CentOS
#   sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# Microsoft Windows
#   python -m pip install pyaudio

import nls
import time

# 设置打开日志输出
nls.enableTrace(False)

# 将音频保存进文件
SAVE_TO_FILE = True
# 将音频通过播放器实时播放,需要具有声卡。在服务器上运行请将此开关关闭
PLAY_REALTIME_RESULT = True
if PLAY_REALTIME_RESULT:
    import pyaudio

test_text = [
    "流式文本语音合成SDK,",
    "可以将输入的文本",
    "合成为语音二进制数据,",
    "相比于非流式语音合成,",
    "流式合成的优势在于实时性",
    "更强。用户在输入文本的同时",
    "可以听到接近同步的语音输出,",
    "极大地提升了交互体验,",
    "减少了用户等待时间。",
    "适用于调用大规模",
    "语言模型(LLM),以",
    "流式输入文本的方式",
    "进行语音合成的场景。",
]

if __name__ == "__main__":
    if SAVE_TO_FILE:
        file = open("output.wav", "wb")
    if PLAY_REALTIME_RESULT:
        player = pyaudio.PyAudio()
        stream = player.open(
            format=pyaudio.paInt16, channels=1, rate=24000, output=True
        )

    # 创建SDK实例
    # 配置回调函数
    def test_on_data(data, *args):
        if SAVE_TO_FILE:
            file.write(data)
        if PLAY_REALTIME_RESULT:
            stream.write(data)

    def test_on_message(message, *args):
        print("on message=>{}".format(message))

    def test_on_close(*args):
        print("on_close: args=>{}".format(args))

    def test_on_error(message, *args):
        print("on_error message=>{} args=>{}".format(message, args))

    sdk = nls.NlsStreamInputTtsSynthesizer(
        # 由于目前阶段大模型音色只在北京地区服务可用,因此需要调整url到北京
        url="wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1",
        token="your-token",
        appkey="your-appkey",
        on_data=test_on_data,
        on_sentence_begin=test_on_message,
        on_sentence_synthesis=test_on_message,
        on_sentence_end=test_on_message,
        on_completed=test_on_message,
        on_error=test_on_error,
        on_close=test_on_close,
        callback_args=[],
    )

    # 发送文本消息
    sdk.startStreamInputTts(
        voice="longxiaochun",       # 语音合成说话人
        aformat="wav",              # 合成音频格式
        sample_rate=24000,          # 合成音频采样率
        volume=50,                  # 合成音频的音量
        speech_rate=0,              # 合成音频语速
        pitch_rate=0,               # 合成音频的音调
    )
    for text in test_text:
        sdk.sendStreamInputTts(text)
        time.sleep(0.05)
    sdk.stopStreamInputTts()
    if SAVE_TO_FILE:
        file.close()
    if PLAY_REALTIME_RESULT:
        stream.stop_stream()
        stream.close()
        player.terminate()

常见SDK错误码

更多错误码详情参见错误码查询