菜单

阿里云语音合成服务使用

发布于 2025年04月29日

开通服务

如果是第一次使用需要注册账户并实名认证,然后开通语音交互服务

[注册链接]阿里云-计算,为了无法计算的价值

打开控制台创建项目

什么是智能语音交互_智能语音交互(ISI)-阿里云帮助中心

智能语音交互控制台

配置一下语音合成,然后就可以在线使用语音合成了,普通语音合成服务对单次请求的文本长度有严格的字符限制,最大为300字符(包括汉字、英文字母、标点符号和空格等)。如果提交的文本超过300字符,超出部分会被截断。

长文本语音合成

长文本语音合成是专门为超长文本设计的服务,支持一次性合成最高 10万字符 的文本。具体规则如下:

  • 单次请求支持的最大字符数:10万字符(1个汉字、1个英文字母、1个标点或1个句子中间空格均算作1个字符)。

  • 适用场景:适合需要合成千字或万字文本的场景,如新闻播报、小说阅读、视频配音等

长文本语音合成的特点

相比普通语音合成,长文本语音合成具有以下优势:

  • 支持更长文本输入:一次性合成最高10万字符。

  • 合成速度快:每合成5万字符最快仅需10分钟。

  • 循环使用:合成后的音频文件支持应用端缓存,可重复使用。

  • 专属声音:按场景打造专属精品声音,贴合不同场景需求(如阅读小说、新闻、视频配音等)。

  • 存储时间:合成结果在3小时内完成,音频文件在服务端可保存7天。


重要限制与注意事项

  • 长文本语音合成 不支持在控制台测试 ,因为控制台的普通语音合成有300字符的限制,超出部分会被截断。

  • 使用长文本语音合成功能时,需要通过长文本语音合成接口调用,并确保将SDK更新至最新版本。

  • 异步获取结果:长文本语音合成仅支持异步方式获取合成结果,详情请参见试用版升级为商用版的相关说明。


计费规则

长文本语音合成的计费方式按照 每万字 进行收费,具体梯度价格如下:

  • 0~19万字:3.00元/万字。

  • 20~99万字:2.80元/万字。

  • 100~999万字:2.60元/万字。

  • 1000~3999万字:2.40元/万字。

  • 4000万字以上:2.20元/万字

异步长文本语音合成调用代码

api文档长文本语音合成接口说明_智能语音交互(ISI)-阿里云帮助中心

#安装依赖包pip install aliyun-python-sdk-core-v3==2.13.10
#将代码中的yourak yoursk替换成自己的ak sk
#appkey是在语音服务控制台中创建的项目key 也要替换成你自己的
import http.client
import urllib.request
import json
import time
import os
import time
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest


class TtsHeader:
    def __init__(self, appkey, token):
        self.appkey = appKey
        self.token = token

    def tojson(self, e):
        return {'appkey': e.appkey, 'token': e.token}


class TtsContext:
    def __init__(self, device_id):
        self.device_id = device_id
    # 将序列化函数定义到类中。

    def tojson(self, e):
        return {'device_id': e.device_id}


class TtsRequest:
    def __init__(self, voice, sample_rate, format, enable_subtitle, text):
        self.voice = voice
        self.sample_rate = sample_rate
        self.format = format
        self.enable_subtitle = enable_subtitle
        self.text = text

    def tojson(self, e):
        return {'voice': e.voice, 'sample_rate': e.sample_rate, 'format': e.format, 'enable_subtitle': e.enable_subtitle, 'text': e.text}


class TtsPayload:
    def __init__(self, enable_notify, notify_url, tts_request):
        self.enable_notify = enable_notify
        self.notify_url = notify_url
        self.tts_request = tts_request

    def tojson(self, e):
        return {'enable_notify': e.enable_notify, 'notify_url': e.notify_url, 'tts_request': e.tts_request.tojson(e.tts_request)}


class TtsBody:
    def __init__(self, tts_header, tts_context, tts_payload):
        self.tts_header = tts_header
        self.tts_context = tts_context
        self.tts_payload = tts_payload

    def tojson(self, e):
        return {'header': e.tts_header.tojson(e.tts_header), 'context': e.tts_context.tojson(e.tts_context), 'payload': e.tts_payload.tojson(e.tts_payload)}
# 根据特定信息轮询检查某个请求在服务端的合成状态,每隔10秒钟轮询一次状态.轮询操作非必须,如果设置了回调url,则服务端会在合成完成后主动回调。


def waitLoop4Complete(url, appkey, token, task_id, request_id):
    # fullUrl = url + "?appkey=" + appkey + "&task_id=" + task_id + "&token=" + token + "&request_id=" + request_id

    fullUrl = url + "?appkey=" + appkey + "&task_id=" + \
        task_id + "&token=" + token + "&request_id=" + request_id

    print("fullUrl=", fullUrl)
    host = {"Host": "nls-gateway-cn-shanghai.aliyuncs.com", "Accept": "*/*",
            "Connection": "keep-alive", 'Content-Type': 'application/json'}
    while True:
        result = urllib.request.urlopen(fullUrl).read()
        print("query result = ", result)
        jsonData = json.loads(result)

        # jsonData["data"]["audio_address"] is None表示还在未合成完成的状态...每隔10秒钟轮询一次状态
        if (jsonData["data"]["audio_address"] is None):
            print(" Tts Queuing...please wait...")
            time.sleep(10)
        elif "error_code" in jsonData and jsonData["error_code"] == 20000000 and "data" in jsonData and (jsonData["data"]["audio_address"] != ""):
            print("Tts Finished! task_id = " + jsonData["data"]["task_id"])
            print("Tts Finished! audio_address = " +
                  jsonData["data"]["audio_address"])
            break

        else:
            print("Tts Running...")
            time.sleep(10)
# 长文本语音合成restful接口,支持post调用,不支持get请求。发出请求后,可以轮询状态或者等待服务端合成后自动回调(如果设置了回调参数)。


def requestLongTts4Post(tts_body, appkey, token):
    host = 'nls-gateway.cn-shanghai.aliyuncs.com'
    url = 'https://' + host + '/rest/v1/tts/async'
    # 设置HTTP Headers
    http_headers = {'Content-Type': 'application/json'}
    print('The POST request body content: ' + tts_body)
    conn = http.client.HTTPSConnection(host)
    #conn = httplib.HTTPConnection(host)
    conn.request(method='POST', url=url, body=tts_body, headers=http_headers)
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status, response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if response.status == 200:
        jsonData = json.loads(body)
        print('The request succeed : ', jsonData)
        print('error_code = ', jsonData['error_code'])
        task_id = jsonData['data']['task_id']
        request_id = jsonData['request_id']
        print('task_id = ', task_id)
        print('request_id = ', request_id)
        # 说明:轮询检查服务端的合成状态,轮询操作非必须。如果设置了回调url,则服务端会在合成完成后主动回调。
        waitLoop4Complete(url, appkey, token, task_id, request_id)
    else:
        print('The request failed: ' + str(body))


# 创建AcsClient实例
client = AcsClient(
   'yourak',
  'yourk',
   "cn-shanghai"
);

# 创建request,并设置参数。
request = CommonRequest()
request.set_method('POST')
request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
request.set_version('2019-02-28')
request.set_action_name('CreateToken')

try : 
   response = client.do_action_with_exception(request)
  ### print(response)

   jss = json.loads(response)
   if 'Token' in jss and 'Id' in jss['Token']:
      token = jss['Token']['Id']
      expireTime = jss['Token']['ExpireTime']
     ### print("token = " + token)
     ### print("expireTime = " + str(expireTime))
except Exception as e:
   print(e)

appKey = 'yourappkey'
## token = ''

##text = '今天是周一,天气挺好的。'
# 读取文件并赋值给变量
text= ''
try:
    with open("离婚之后.txt", "r",) as f:
        text = f.read().strip()
    #print("读取成功:", text)
except Exception as e:
    print("错误:", str(e))
# 拼接HTTP Post请求的消息体内容。
th = TtsHeader(appKey, token)
tc = TtsContext("mydevice")
# TtsRequest对象内容为:发音人、采样率、语音格式、待合成文本内容。
tr = TtsRequest("xiaoyun", 16000, "wav", False, text)
# 是否设置回调url,回调url地址,TtsRequest对象。
tp = TtsPayload(True, "http://134.com", tr)
tb = TtsBody(th, tc, tp)
body = json.dumps(tb, default=tb.tojson)
requestLongTts4Post(str(body), appKey, token)

运行代码

控制台可以看到调用量



评论