阿里云+tp5.1 實作語音合成(文字轉音頻)大🐂請忽略!!!
效果視頻鏈接:http://images.junely.vip/textToAudio.mp4
前提條件
-
已準備專案appkey,詳情請參見創建專案,
-
已獲取Access Token,詳情請參見獲取Token,
獲取token前提條件
- 已獲取AccessKey ID和AccessKey Secret,詳情請參見開通服務,
獲取Token代碼:
/**
* 獲取Token
* @return int|mixed|string
* @throws ClientException
*/
public function getToken(){
$cacheToken = cache('AccessToken');
if ($cacheToken) return $cacheToken;
AlibabaCloud::accessKeyClient(
config('aliyun.accessKeyId'), //你的阿里云accessKeyId
config('aliyun.accessKeySecret') //你的阿里云accessKeySecret
)
->regionId("cn-shanghai")
->asDefaultClient();
try {
$response = AlibabaCloud::nlsCloudMeta()
->v20180518()
->createToken()
->request();
$token = $response["Token"];
if($token) {
cache('AccessToken',$response["Token"]['Id'],3600); //存快取
return $response["Token"]['Id']; //Token在此
}
return 0;
} catch (ClientException $exception) {
// 獲取錯誤訊息
return $exception->getErrorMessage();
} catch (ServerException $exception) {
// 獲取錯誤訊息
return $exception->getErrorMessage();
}
}
控制器代碼:
<?php
namespace app\index\controller;
use app\index\model\Index as I;
class Index extends Base
{
public function index()
{
$data = (new I())->index();
$this->assign('file', $data);
return $this->fetch();
}
}
模型代碼:
public function index(){
$text = input('post.text');
$appkey = config('aliyun.appKey'); //專案AppKey
$token = $this->getToken();
$audioSaveFile = date('YmdHis').".wav"; //檔案名
$format = "wav";
$sampleRate = 16000;
$res = $this->processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate);
return ($res);
}
public function processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate)
{
$url = "nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts";
/**
* 請求引數,以JSON格式字串填入HTTPS POST請求的Body中,
*/
$taskArr = array(
"appkey" => $appkey,
"token" => $token,
"text" => $text,
"format" => $format,
"sample_rate" => $sampleRate,
// voice 發音人,可選,默認是xiaoyun,
"voice" => "Aida",
// volume 音量,范圍是0~100,可選,默認50,
"volume" => 50,
// speech_rate 語速,范圍是-500~500,可選,默認是0,
"speech_rate" => -350,
// pitch_rate 語調,范圍是-500~500,可選,默認是0,
"pitch_rate" => 50
);
/**
* 陣列轉json,中文不轉義
*/
$body = json_encode($taskArr,JSON_UNESCAPED_UNICODE);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
/**
* 設定HTTPS POST URL,
*/
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
/**
* 設定HTTPS POST請求頭部,
* */
$httpHeaders = array(
"Content-Type: application/json"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
/**
* 設定HTTPS POST請求體,
*/
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
/**
* 設定回傳的回應包含HTTPS頭部資訊,
*/
curl_setopt($curl, CURLOPT_HEADER, TRUE);
/**
* 發送HTTPS POST請求,
*/
$response = curl_exec($curl);
if ($response == FALSE) {
curl_close($curl);
return 'curl_exec failed!';
}
/**
* 處理服務端回傳的回應,
*/
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$bodyContent = substr($response, $headerSize);
curl_close($curl);
if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
// $res = file_put_contents('audioFile/'.$audioSaveFile, $bodyContent); //寫入檔案輸出到本地
//轉成base64格式
$base64String = 'data:' . 'audio/mpeg' . ';base64,' . chunk_split(base64_encode($bodyContent));
return $base64String;
}
}
視圖:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<audio src="{$file}" controls="controls"></audio>
</body>
</html>
(文筆不好,請勿介意)~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/226337.html
標籤:其他
