来分享下PHP调用科大讯飞在线语音合成接口生成语音文件
在后台新建应用,添加IP白名单,复制APPID 与 APIKey备用
定义APPID与APPKEY
const APP_ID = 'xxx'; //APPID const APP_KEY_TTS = 'xxxxxxx'; //语音合成APPKEY
语音生成函数
public function voiceTts($content, $output_path)
{
$param = [
'auf' => 'audio/L16;rate=16000', //音频采样率
'aue' => 'lame', //格式
'voice_name' => 'xiaoyan', //发音人
'speed' => '50', //语速
'volume' => '50', //音量
'pitch' => '50', //音高
'engine_type' => 'intp65', //中文
];
$cur_time = (string)time();
$x_param = base64_encode(json_encode($param));
$header_data = [
'X-Appid:' . self::APP_ID,
'X-CurTime:' . $cur_time,
'X-Param:' . $x_param,
'X-CheckSum:' . md5(self::APP_KEY_TTS . $cur_time . $x_param),
'Content-Type:application/x-www-form-urlencoded; charset=utf-8'
]; //Body
$body_data = 'text=' . urlencode($content); //Request
$url = "http://api.xfyun.cn/v1/service/v1/tts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_data);
$result = curl_exec($ch);
$res_header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$res_header = substr($result, 0, $res_header_size);
curl_close($ch);
if (stripos($res_header, 'Content-Type: audio/mpeg') === FALSE) { //合成错误
return json_decode(substr($result, $res_header_size),true);
} else {
file_put_contents($output_path, substr($result, $res_header_size));
return array('code'=>0);
}
}
调用
voiceTts("葫芦娃", 'demo.mp3');