随着人工智能技术的飞速发展,人机交互的方式也在不断革新。腾讯云语音合成(TTS)技术,作为AI领域的一项重要应用,正在以前所未有的速度改变我们的生活和工作方式。大家好,我是AI大眼萌,今天就让我们一起探索这项技术的魅力和潜力!
在人工智能的世界里,ASR(Automatic Speech Recognition)和TTS(Text-To-Speech)是一对默契的搭档。ASR,就像人类的耳朵,能够将声音转化为文字;而TTS,仿佛人类的嘴巴,将文字转化为声音。就像我们熟悉的Siri,那些流畅的语音回复,其实都是TTS技术在背后默默工作的结果。TTS的实现方法主要有两种:拼接法和参数法。
拼接法,就像是用预先录制好的语音片段,像拼图一样拼接出想要的语音。这种方法使用的基本单位可能是音节、音素,甚至是双音子,以确保合成语音的连贯性。它的优点显而易见——语音质量高,但缺点也同样明显:需要庞大的数据库支持,成本高昂。
参数法则是另一种魔法,它依据统计模型生成语音参数,再将这些参数转化为波形。这个过程包括前端处理、建模和声码器三个模块。前端处理负责解析文本,决定发音、语气、节奏等,而声码器则是复现声音信号的关键环节。
前端处理,就像是文本的解析者,它决定了每个字的发音,语气语调,甚至是需要强调的重点。尽管目前的算法还无法完全捕捉所有的细节,但它已经能够处理包括韵律边界、重音、边界调等在内的多种语气相关数据。
个性化TTS,大多数采用参数法实现,它可以根据需求定制出独特的声音。虽然Adobe和微软等大公司也尝试过拼接法,但参数法因其通用性和成熟度更受青睐。
import os
from dotenv import load_dotenv
root_dir='/mnt/workspace/'
load_dotenv(os.path.join(root_dir, "TTS.env"))
APPID =os.getenv('APPID')
SECRET_ID =os.getenv('SECRET_ID')
SECRET_KEY =os.getenv('SECRET_KEY')
#定义函数,通过网页获取语音文件
import hmac
import hashlib
import json
import time
from datetime import datetime
from uuid import uuid4
import base64
from http.client import HTTPSConnection
from IPython.display import Audio
import io
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
TEXT = """请相信,每一个努力的瞬间,都是你人生故事中不可或缺的篇章。
"""
VOICETYPE = 301006 # 音色类型
CODEC = "wav" # 音频格式:pcm/mp3
SAMPLE_RATE = 16000 # 音频采样率:8000/16000
ENABLE_SUBTITLE = True
def text_to_speech(text, voice_type=VOICETYPE, sample_rate=SAMPLE_RATE, codec=CODEC, enable_subtitle=ENABLE_SUBTITLE,EmotionCategory='sad'):
service = "tts"
host = "tts.tencentcloudapi.com"
region = "ap-shanghai"
version = "2019-08-23"
action = "TextToVoice"
token = ""
# 使用提供的参数更新 payload 字典
payload = {
"Text": text,
"VoiceType": voice_type,
"SampleRate": sample_rate,
"Codec": codec,
"EnableSubtitle": enable_subtitle,
"EmotionCategory": EmotionCategory,
"SessionId": str(uuid4()) # 生成唯一会话 ID
}
params = json.dumps(payload)
endpoint = "https://tts.tencentcloudapi.com"
algorithm = "TC3-HMAC-SHA256"
timestamp = int(time.time())
date = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d")
# ************* 步骤 1:拼接规范请求串 *************
http_request_method = "POST"
canonical_uri = "/"
canonical_querystring = ""
ct = "application/json; charset=utf-8"
canonical_headers = "content-type:%s\nhost:%s\nx-tc-action:%s\n" % (ct, host, action.lower())
signed_headers = "content-type;host;x-tc-action"
hashed_request_payload = hashlib.sha256(params.encode("utf-8")).hexdigest()
canonical_request = (http_request_method + "\n" +
canonical_uri + "\n" +
canonical_querystring + "\n" +
canonical_headers + "\n" +
signed_headers + "\n" +
hashed_request_payload)
# ************* 步骤 2:拼接待签名字符串 *************
credential_scope = date + "/" + service + "/" + "tc3_request"
hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
string_to_sign = (algorithm + "\n" +
str(timestamp) + "\n" +
credential_scope + "\n" +
hashed_canonical_request)
# ************* 步骤 3:计算签名 *************
secret_date = sign(("TC3" + SECRET_KEY).encode("utf-8"), date)
secret_service = sign(secret_date, service)
secret_signing = sign(secret_service, "tc3_request")
signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
# ************* 步骤 4:拼接 Authorization *************
authorization = (algorithm + " " +
"Credential=" + SECRET_ID + "/" + credential_scope + ", " +
"SignedHeaders=" + signed_headers + ", " +
"Signature=" + signature)
# ************* 步骤 5:构造并发起请求 *************
headers = {
"Authorization": authorization,
"Content-Type": "application/json; charset=utf-8",
"Host": host,
"X-TC-Action": action,
"X-TC-Timestamp": timestamp,
"X-TC-Version": version
}
if region:
headers["X-TC-Region"] = region
if token:
headers["X-TC-Token"] = token
print('start-----')
try:
req = HTTPSConnection(host)
req.request("POST", "/", headers=headers, body=params.encode("utf-8"))
resp = req.getresponse()
# 假设我们成功获取了音频数据并保存到了 audio_file_path
# 解码 JSON 响应体
response_json = json.loads(resp.read().decode('utf-8'))
# # 获取 Base64 编码的音频数据
base64_audio = response_json['Response']
return base64_audio
except Exception as err:
print(err)
#输出结果
参数配置可参考官方教程:https://cloud.tencent.com/document/product/1073/37995#.E7.A4.BA.E4.BE.8B1-.E5.9F.BA.E7.A1.80.E8.AF.AD.E9.9F.B3.E5.90.88.E6.88.90.E8.B0.83.E7.94.A8.E7.A4.BA.E4.BE.8B
rest=text_to_speech(TEXT,VOICETYPE, SAMPLE_RATE,CODEC,ENABLE_SUBTITLE)
Audio(base64.b64decode(rest['Audio'].encode("utf-8")), autoplay=True)
腾讯云语音合成技术,正在开启智能语音的新纪元。它不仅仅是技术的突破,更是对人类生活方式的一次深刻变革。让我们一起期待并探索,TTS技术将如何进一步丰富我们的世界!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。