第一步:composer 引入SDK
composer require tencentcloud/tencentcloud-sdk-php
安装完成以后如下图目录可见
第二步:
项目中新建控制器 我是用的是index控制器
<?php
namespace app\index\controller;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Tts\V20190823\TtsClient;
use TencentCloud\Tts\V20190823\Models\CreateTtsTaskRequest;
use TencentCloud\Tts\V20190823\Models\TextToVoiceRequest;
use think\facade\Env;
class Index
{
public function speechSynthesis()
{
try {
$cred = new Credential(config("SecretId"), config("SecretKey"));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("tts.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new TtsClient($cred, "ap-guangzhou", $clientProfile);
$vname=md5(time().rand(10000,90000)); //搞个随机字符串api调用时需要到的参数,同时也是mp3文件日后的文件名了
# 长文本语音类
// $req = new CreateTtsTaskRequest();
# 基础语音合成类
$req = new TextToVoiceRequest();
$params = [
'Text' => '内容',
'ModelType' => 1,
'SessionId' => $vname,
'VoiceType' => 1001,
'Timestamp' => time(),
'Codec' => 'mp3'
];
$params = json_encode($params,true);
$req->fromJsonString($params);
# 调用长文本转语音mp3
// $resp = $client->CreateTtsTask($req);
# 调用基础文本转语音mp3
$resp = $client->TextToVoice($req);
$resp=$resp->toJsonString();
$resp=json_decode($resp,true); //到这里已经得到了返回的数据但转成数组了
$path = $vname.'.mp3';
$myfile = fopen(Env::get('root_path')."\public\\upload\\".$path, "w") or die("Unable to open file!");
fwrite($myfile, base64_decode($resp['Audio'])); //base64_decode是因为返回来的音频数据需解码后保存出来的mp3文件才正常
fclose($myfile);
echo "合成文件成功";
}catch (TencentCloudSDKException $e){
echo $e;
}
}
}
生成的mp3可播放文件放在了 public/upload文件夹下
SDK中可支持长文本转换语音和基础文本转换语音 详情请看官方文档语音合成 基础语音合成-API 文档-文档中心-腾讯云