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

 $appKey,
            self::KEY_FILE_LINK => $fileLink,
            self::KEY_VERSION => "4.0",
            self::KEY_ENABLE_WORDS => FALSE,
            // @ref: https://help.aliyun.com/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()
            ->v20180817()
            ->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()
                ->v20180817()
                ->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;
    }
}

调用:

regionId("cn-shanghai")
            ->asGlobalClient();

        $fileTrans = new NLSFileTrans();
        /**
         * @var $appKeyId string
         * @ref: https://nls-portal.console.aliyun.com/applist 我的所有项目(不是access key)
         * 确认开通了asr+tts服务
         * https://nls-portal.console.aliyun.com/
         */
        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;
    }
}

你可能感兴趣的:(流媒体,php,阿里云,云计算)