'mp3', 4 => 'pcm', 5 =>'pcm', 6 => 'wav'); $format = $formats[$aue]; $cuid = time(); /** 公共模块获取token开始 */ $auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$apiKey."&client_secret=".$secretKey; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $auth_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,0不验证 curl_setopt($ch, CURLOPT_VERBOSE, false); $res = curl_exec($ch); if(curl_errno($ch)) { print curl_error($ch); } curl_close($ch); $response = json_decode($res, true); if (!isset($response['access_token'])){ echo "ERROR TO OBTAIN TOKEN\n"; exit(1); } if (!isset($response['scope'])){ echo "ERROR TO OBTAIN scopes\n"; exit(2); } if (!in_array('audio_tts_post',explode(" ", $response['scope']))){ echo "DO NOT have tts permission\n"; // 请至网页上应用内开通语音合成权限 exit(3); } $token = $response['access_token']; /** 公共模块获取token结束 */ /** 拼接参数开始 **/ // tex=$text&lan=zh&ctp=1&cuid=$cuid&tok=$token&per=$per&spd=$spd&pit=$pit&vol=$vol $params = array( 'tex' => urlencode($text), // 为避免+等特殊字符没有编码,此处需要2次urlencode。 'per' => $per, 'spd' => $spd, 'pit' => $pit, 'vol' => $vol, 'aue' => $aue, 'cuid' => $cuid, 'tok' => $token, 'lan' => 'zh', //固定参数 'ctp' => 1, // 固定参数 ); $paramsStr = http_build_query($params); $url = 'http://tsn.baidu.com/text2audio'; $urltest = $url . '?' . $paramsStr; //echo $urltest . "\n"; // 反馈请带上此url return $urltest; //die; /** 拼接参数结束 **/ $g_has_error = true; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsStr); function read_header($ch, $header){ global $g_has_error; $comps = explode(":", $header); // 正常返回的头部 Content-Type: audio/* // 有错误的如 Content-Type: application/json if (count($comps) >= 2){ if (strcasecmp(trim($comps[0]), "Content-Type") == 0){ if (strpos($comps[1], "audio/") > 0 ){ $g_has_error = false; }else{ echo $header ." , has error \n"; } } } return strlen($header); } //echo $urltest . "\n"; // 反馈请带上此urlcurl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header'); $data = curl_exec($ch); if(curl_errno($ch)) { echo curl_error($ch); exit(2); } curl_close($ch); echo $urltest . "\n"; // 反馈请带上此url die; $file = $g_has_error ? "result.txt" : "result." . $format; file_put_contents($file, $data); echo "\n$file saved successed, please open it \n"; } }