1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 阿里云ASR 语音识别接口调用

阿里云ASR 语音识别接口调用

时间:2018-08-19 08:55:23

相关推荐

阿里云ASR 语音识别接口调用

<?phpnamespace App\Helpers\Utils\Alibaba;use AlibabaCloud\Client\AlibabaCloud;use AlibabaCloud\Client\Exception\ClientException;use AlibabaCloud\Client\Exception\ServerException;use Illuminate\Support\Facades\Log;class NLSFileTrans {// 请求参数private const KEY_APP_KEY = "appkey";private const KEY_FILE_LINK = "file_link";private const KEY_VERSION = "version";private const KEY_ENABLE_WORDS = "enable_words";// 响应参数private const KEY_TASK_ID = "TaskId";private const KEY_STATUS_TEXT = "StatusText";private const KEY_RESULT = "Result";// 状态值private const STATUS_SUCCESS = "SUCCESS";private const STATUS_RUNNING = "RUNNING";private const STATUS_QUEUEING = "QUEUEING";public function submitFileTransRequest(string $appKey, $fileLink) {// 获取task JSON字符串,包含appkey和file_link参数等。// 新接入请使用4.0版本,已接入(默认2.0)如需维持现状,请注释掉该参数设置。// 设置是否输出词信息,默认为false,开启时需要设置version为4.0。$taskArr = array(self::KEY_APP_KEY => $appKey,self::KEY_FILE_LINK => $fileLink,self::KEY_VERSION => "4.0",self::KEY_ENABLE_WORDS => FALSE,// @ref: /document_detail/90727.html#sectiondiv-qto-pl7-lvd// 检查实际语音的采样率和控制台上Appkey绑定的ASR模型采样率是否一致"enable_sample_rate_adaptive" => true,);$task = json_encode($taskArr);Log::debug($task);// 提交请求,返回服务端的响应。$submitTaskResponse = AlibabaCloud::nlsFiletrans()->v0817()->submitTask()->withTask($task)->request();Log::info($submitTaskResponse);// 获取录音文件识别请求任务的ID,以供识别结果查询使用。$taskId = NULL;$statusText = $submitTaskResponse[self::KEY_STATUS_TEXT];if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {$taskId = $submitTaskResponse[self::KEY_TASK_ID];}return $taskId;}public function getFileTransResult($taskId) {$result = NULL;try {$getResultResponse = AlibabaCloud::nlsFiletrans()->v0817()->getTaskResult()->withTaskId($taskId)->request();Log::notice("识别查询结果: " . json_encode($getResultResponse));// $statusText = $getResultResponse[self::KEY_STATUS_TEXT];// if (strcmp(self::STATUS_RUNNING, $statusText) == 0 || strcmp(self::STATUS_QUEUEING, $statusText) == 0) {}// else {if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {$result = $getResultResponse;}}$result = $getResultResponse;} catch (ClientException $exception) {// 获取错误消息print_r($exception->getErrorMessage());} catch (ServerException $exception) {// 获取错误消息print_r($exception->getErrorMessage());}return $result;}}

调用:

<?phpnamespace App\Services;use AlibabaCloud\Client\AlibabaCloud;use AlibabaCloud\Client\Exception\ClientException;use AlibabaCloud\Client\Exception\ServerException;use App\Enums\ErrorCode;use App\Helpers\Utils\Alibaba\NLSFileTrans;use App\Helpers\Utils\Alibaba\OSS;use App\Models\Work;use Spatie\Permission\Exceptions\UnauthorizedException;class ApiService{/*** 提交录音文件识别请求,获取任务ID* @param string $fileLink* @return array*/public function asrCreateTask(string $fileLink) {$accessKeyId = config('constant.alibaba_access_key_id');$accessKeySecret = config('constant.alibaba_access_key_secret');$appKey = config('constant.alibaba_app_key');/*** 第一步:设置一个全局客户端。* 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。*/AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId("cn-shanghai")->asGlobalClient();$fileTrans = new NLSFileTrans();/*** @var $appKeyId string* @ref: https://nls-portal./applist 我的所有项目(不是access key)* 确认开通了asr+tts服务* https://nls-portal./*/try {$taskId = $fileTrans->submitFileTransRequest($appKey, $fileLink);if ($taskId != NULL) {$msg = "录音文件识别请求成功";return ['message' => $msg, 'code' => ErrorCode::OK, 'result' => ['task_id'=>$taskId], 'time'=>time()];}} catch (ClientException $e) {// 获取错误消息return ['message' => "failed", 'code'=> $e->getErrorCode(), 'error'=>$e->getErrorMessage()];} catch (ServerException $e) {return ['message' => "failed", 'code'=> $e->getErrorCode(), 'error'=>$e->getErrorMessage()];}return ['message'=>"failed", 'code'=> ErrorCode::API_ERROR, 'error'=>"语音识别任务创建失败"];}/*** 异步查询ASR任务结果* @param string $taskId* @return array* @throws ClientException*/public function asrQuery(string $taskId) {$accessKeyId = config('constant.alibaba_access_key_id');$accessKeySecret = config('constant.alibaba_access_key_secret');/*** 第一步:设置一个全局客户端。* 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。*/AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId("cn-shanghai")->asGlobalClient();$fileTrans = new NLSFileTrans();/*** 第三步:根据任务ID轮询识别结果。* @var $result \AlibabaCloud\Client\Result\Result*/$result = $fileTrans->getFileTransResult($taskId);if (is_null($result)) {return ['message'=>"failed", 'code'=> ErrorCode::API_ERROR, 'error'=>"录音文件识别结果查询失败!",'time'=>time()];}/** @var $s string JSON string */$s = $result->toJson();header("Content-Type: application/json");echo $s;exit(0);}public function fetchWork(int $workId, int $memberId, string $downloadType = 'wav') {/** @var $work Work */$work = Work::find($workId);if (empty($work)) {throw new \InvalidArgumentException("作品ID不存在", ErrorCode::PARAM_ERROR);}if (0 != $work->getMemberId()-$memberId) {throw new UnauthorizedException(ErrorCode::PERMISSION_DENIED, "只能下载自己的作品");}return $work;}public function upload(string $path, string $ext, string $bucket) {$oss = new OSS();$filename = md5_file($path);$uri = sprintf("%s/%s.%s", date("Y-m-d", time()), $filename, $ext);$oss->bucket($bucket)->upload($uri, $path, $bucket);return "https://".$bucket.".".OSS::END_POINT."/".$uri;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。