作者 何书鹏
1 个管道 的构建 通过 耗费 0 秒

语音转文字

... ... @@ -364,8 +364,16 @@ class Almighty extends Api
public function getText()
{
$filename = $this->request->param('filename');
$res = $this->mp3ToPcm($filename);
$this->success('成功');
empty($filename) && $this->error('请输入音频地址');
$suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
if (!in_array($suffix, ['pcm', 'wav', 'amr', 'm4a', 'mp3'])) {
$this->error('不支持该音频格式');
}
if($suffix == 'mp3'){
$filename = $this->mp3ToPcm($filename);
}
$result = $this->asrJson($filename);
$this->success('成功',['text'=>$result]);
}
/**
... ... @@ -488,14 +496,12 @@ class Almighty extends Api
}
/**
* 上传接口
* mp3转pcm
* @ApiInternal
*/
public function mp3ToPcm($filename)
{
$key = ltrim($filename,'/');
if(pathinfo($key,PATHINFO_EXTENSION) != 'mp3'){
return false;
}
$config = get_addon_config('qiniu');
$auth = new Auth($config['app_key'], $config['secret_key']);
//设置转码参数
... ... @@ -508,7 +514,8 @@ class Almighty extends Api
$fops = $fops.'|saveas/'.$saveas_key;
$policy = array(
'persistentOps' => $fops
'persistentOps' => $fops,
'persistentNotifyUrl' => $this->request->root(true) . '/mobile/notify/notifyQiniu',
);
$token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
$multipart = [
... ... @@ -524,13 +531,139 @@ class Almighty extends Api
$res = $client->request('POST', $config['uploadurl'], [
'multipart' => $multipart
]);
// halt($res);
$code = $res->getStatusCode();
halt($code);
//成功不做任何操作
} catch (\GuzzleHttp\Exception\ClientException $e) {
return false;
$this->error("上传失败");
}
return '/' . $filename . '.pcm';
}
/**
* 语音转文字
* @ApiInternal
*/
public function asrJson($filename){
define('DEMO_CURL_VERBOSE', false); // 打印curl debug信息
# 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
$API_KEY = "kVcnfD9iW2XVZSMaLMrtLYIz";
# 填写网页上申请的APP SECRET 如 $secretKey="94dc99566550d87f8fa8ece112xxxxx"
$SECRET_KEY = "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6";
# 需要识别的文件
$AUDIO_FILE = $filename;
# 文件格式
$FORMAT = substr($AUDIO_FILE, -3); // 文件后缀 pcm/wav/amr 格式 极速版额外支持m4a 格式
$CUID = "123456PHP";
# 采样率
$RATE = 16000; // 固定值
# 普通版
$ASR_URL = "http://vop.baidu.com/server_api";
# 根据文档填写PID,选择语言及识别模型
$DEV_PID = 1537; // 1537 表示识别普通话,使用输入法模型。
$SCOPE = 'audio_voice_assistant_get'; // 有此scope表示有语音识别普通版能力,没有请在网页里开通语音识别能力
#测试自训练平台需要打开以下信息, 自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234
//$DEV_PID = 8001 ;
//$LM_ID = 1234 ;
# 极速版需要打开以下信息 打开注释的话请填写自己申请的appkey appSecret ,并在网页中开通极速版(开通后可能会收费)
//$ASR_URL = "http://vop.baidu.com/pro_api";
//$DEV_PID = 80001;
//$SCOPE = 'brain_enhanced_asr'; // 有此scope表示有极速版能力,没有请在网页里开通极速版
$SCOPE = false; // 部分历史应用没有加入scope,设为false忽略检查
/** 公共模块获取token开始 */
$auth_url = "http://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$API_KEY."&client_secret=".$SECRET_KEY;
$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, DEMO_CURL_VERBOSE);
$res = curl_exec($ch);
if(curl_errno($ch))
{
$this->error(curl_error($ch));
}
curl_close($ch);
echo "Token URL response is " . $res . "\n";
$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 ($SCOPE && !in_array($SCOPE, explode(" ", $response['scope']))){
echo "CHECK SCOPE ERROR\n";
// 请至网页上应用内开通语音识别权限
exit(3);
}
$token = $response['access_token'];
/** 公共模块获取token结束 */
/** 拼接参数开始 **/
$audio = file_get_contents($AUDIO_FILE);
$base_data = base64_encode($audio);
$params = array(
"dev_pid" => $DEV_PID,
//"lm_id" => $LM_ID, //测试自训练平台开启此项
"format" => $FORMAT,
"rate" => $RATE,
"token" => $token,
"cuid"=> $CUID,
"speech" => $base_data,
"len" => strlen($audio),
"channel" => 1,
);
$json_array = json_encode($params);
$headers[] = "Content-Length: ".strlen($json_array);
$headers[] = 'Content-Type: application/json; charset=utf-8';
/** 拼接参数结束 **/
/** asr 请求开始 **/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ASR_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 识别时长不超过原始音频
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_array);
curl_setopt($ch, CURLOPT_VERBOSE, DEMO_CURL_VERBOSE);
$res = curl_exec($ch);
if(curl_errno($ch))
{
$this->error(curl_error($ch));
}
curl_close($ch);
// 解析结果
$response = json_decode($res, true);
if (isset($response['err_no']) && $response['err_no'] == 0){
return $response['result'][0];
}else{
$this->error($response['err_msg']);
}
return $code;
}
}
\ No newline at end of file
... ...
... ... @@ -8,7 +8,7 @@ use app\mobile\model\SecretOrder;
use app\mobile\model\ScoreOrder;
/**
* 支付异步接口
* 异步接口
* @ApiInternal
*/
class Notify extends Api
... ... @@ -100,4 +100,47 @@ class Notify extends Api
}
echo $pay->success();
}
/**
* 七牛云通知回调
* @ApiInternal
*/
public function notifyQiniu()
{
$config = get_addon_config('qiniu');
$auth = new Auth($config['app_key'], $config['secret_key']);
$contentType = 'application/x-www-form-urlencoded';
$authorization = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
if (!$authorization && function_exists('apache_request_headers')) {
$headers = apache_request_headers();
$authorization = isset($headers['Authorization']) ? $headers['Authorization'] : '';
}
$url = $this->request->root(true) . '/mobile/notify/notifyQiniu';
$body = file_get_contents('php://input');
$ret = $auth->verifyCallback($contentType, $authorization, $url, $body);
if ($ret) {
parse_str($body, $arr);
$admin_id = isset($arr['admin']) ? $arr['admin'] : 0;
$user_id = isset($arr['user']) ? $arr['user'] : 0;
$imageInfo = json_decode($arr['imageInfo'], true);
$params = array(
'admin_id' => (int)$admin_id,
'user_id' => (int)$user_id,
'filesize' => $arr['filesize'],
'imagewidth' => isset($imageInfo['width']) ? $imageInfo['width'] : 0,
'imageheight' => isset($imageInfo['height']) ? $imageInfo['height'] : 0,
'imagetype' => isset($imageInfo['format']) ? $imageInfo['format'] : '',
'imageframes' => 1,
'mimetype' => "image/" . (isset($imageInfo['format']) ? $imageInfo['format'] : ''),
'extparam' => '',
'url' => '/' . $arr['key'],
'uploadtime' => time(),
'storage' => 'qiniu'
);
Attachment::create($params);
return json(['ret' => 'success', 'code' => 1, 'data' => ['url' => $params['url']]]);
}
return json(['ret' => 'failed']);
}
}
\ No newline at end of file
... ...