<?php
/**
* Created by PhpStorm.
* User: FZS
* Time: 2019/3/13 17:10
*/
//----------------------------------
// 百度语音识别调用类
//----------------------------------
class freeApi{
private $apiKey = false; //百度应用AppID
private $secretKey = false; //百度应用API Key
private $tokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
private $apiUrl = 'https://vop.baidu.com/server_api';
public function __construct($apikey,$secretkey){
$this->apiKey = $apikey;
$this->secretKey = $secretkey;
}
/**
* 获取token
* @return array
*/
public function getToken(){
$params = [
'grant_type' => 'client_credentials',
'client_id' => $this->apiKey,
'client_secret' => $this->secretKey,
];
$o = "";
foreach ( $params as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$params = substr($o,0,-1);
return $this->returnArray($this->freeApiCurl($this->tokenUrl,$params,1));
}
/**
* 将JSON内容转为数据,并返回
* @param string $content [内容]
* @return array
*/
public function returnArray($content){
return json_decode($content,true);
}
/**
* 获取结果
* @return array
*/
public function getResult(){
$speech = file_get_contents('http://speech-doc.gz.bcebos.com/rest-api-asr/public_audio/16k.pcm');
$len = strlen($speech);
$params = [
'format' => 'pcm',
'rate' => 16000,
'dev_pid' => 1536,
'channel' => 1,
'token' => $this->getToken()['access_token'],
'cuid' => 'baidu_workshop',
'len' => $len,
'speech' => base64_encode($speech),
];
$params = json_encode($params);
return $this->returnArray($this->jsonPost($this->apiUrl,$params));
}
public function jsonPost($url,$data_json){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
/**
* 请求接口返回内容
* @param string $url [请求的URL地址]
* @param string $params [请求的参数]
* @param int $ipost [是否采用POST形式]
* @return string
*/
public function freeApiCurl($url,$params=false,$ispost=0){
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'free-api' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
if( $ispost )
{
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
curl_setopt( $ch , CURLOPT_URL , $url );
}
else
{
if($params){
curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
}else{
curl_setopt( $ch , CURLOPT_URL , $url);
}
}
$response = curl_exec( $ch );
if ($response === FALSE) {
return false;
}
$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
curl_close( $ch );
return $response;
}
}