<?php
 namespace TechSoft\Laravel\Third; use Illuminate\Support\Facades\Cache; use TechOnline\Laravel\Http\Response; use TechOnline\Utils\CurlUtil; class BaiduAI { private static function getBaiduAccessToken($appKey, $secretKey) { $key = 'Soft:BaiduAI:AccessToken:' . $appKey; $accessToken = Cache::get($key); if (empty($accessToken)) { $ret = CurlUtil::postJSON('http://openapi.baidu.com/oauth/2.0/token', [ 'grant_type' => 'client_credentials', 'client_id' => $appKey, 'client_secret' => $secretKey, ]); if ($ret['code']) { return null; } $accessToken = $ret['data']['access_token']; Cache::put($key, $accessToken, intval($ret['data']['expires_in'] / 60 * 3 / 4)); } return $accessToken; } public static function asr($config, $audioContent) { $accessToken = self::getBaiduAccessToken($config['appKey'], $config['secretKey']); $dev_pid = '1537'; if (!empty($config['param']['baidu']['dev_pid'])) { $dev_pid = $config['param']['baidu']['dev_pid']; } $ret = CurlUtil::postJSON( "http://vop.baidu.com/server_api?cuid=" . time() . "&token=$accessToken&dev_pid=$dev_pid", $audioContent, [ 'header' => [ 'format' => 'wav', 'rate' => '16000', 'Content-Type' => 'audio/wav;rate=16000', ] ] ); if ($ret['code']) { return Response::generate(-1, '识别失败'); } if (empty($ret['data']['result'][0])) { return Response::generate(0, null, [ 'text' => '', ]); } return Response::generate(0, null, [ 'text' => $ret['data']['result'][0], ]); } }