直接可以复制使用的代码,PHP实现调取 百度文字转语音SDK
提示:建议放入助手中使用
public function Index()
{
return getVoiceUrl('俺就是这么帅',2,2,2,3);
}
if (!function_exists("getVoiceUrl")) {
function getVoiceUrl($tex, $spd = 5, $pit = 5, $vol = 5, $per = 0)
{
if (!\Yii::$app->cache->get('voice_key')) {
$token_url = "https://openapi.baidu.com/oauth/2.0/token";
$headers = 'content-type:application/x-www-form-urlencoded';
$params = 'grant_type=client_credentials&client_id=tGkGdWBsFPiyuB0gpgCPA4Zk&client_secret=ElWhGqpgVqIaaCQXcxDG8baXvWzVqutL';
$token = json_decode(juhecurlHttps($token_url, $params, true, $headers));
\Yii::$app->cache->set('voice_key', $token->access_token, $token->expires_in);
}
$url = "http://tsn.baidu.com/text2audio";
$params = [
'tok' => \Yii::$app->cache->get('voice_key'),
'tex' => $tex,
'spd' => $spd,
'pit' => $pit,
'vol' => $vol,
'per' => $per,
'cuid' => "quickstart",
'lan' => 'zh',
'ctp' => 1,
];
if (is_array($params)) {
$url .= '?';
foreach ($params as $k => $v) {
$url .= $k . '=' . $v . '&';
}
}
return $url;
}
}
if (!function_exists('juhecurlHttps')) {
function juhecurlHttps($url, $params = false, $ispost = 0, $headers = [])
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) {
unset($params['zt']);
$url .= '?';
foreach ($params as $k => $v) {
$url .= $k . '=' . $v . '&';
}
curl_setopt($ch, CURLOPT_URL, $url);
} else {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
}
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
if ($response === FALSE) {
return false;
}
curl_close($ch);
return $response;
}
}