找回密码
 免费注册

[阿里云] 阿里云录音文件识别实例DEMO

[复制链接]
admin 发表于 2023-2-17 19:17:28 | 显示全部楼层 |阅读模式
  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. class NLSFileTrans {
  7.     // 请求参数
  8.     private const KEY_APP_KEY = "appkey";
  9.     private const KEY_FILE_LINK = "file_link";
  10.     private const KEY_VERSION = "version";
  11.     private const KEY_ENABLE_WORDS = "enable_words";
  12.     // 响应参数
  13.     private const KEY_TASK_ID = "TaskId";
  14.     private const KEY_STATUS_TEXT = "StatusText";
  15.     private const KEY_RESULT = "Result";
  16.     // 状态值
  17.     private const STATUS_SUCCESS = "SUCCESS";
  18.     private const STATUS_RUNNING = "RUNNING";
  19.     private const STATUS_QUEUEING = "QUEUEING";
  20.     function submitFileTransRequest($appKey, $fileLink) {
  21.         // 获取task JSON字符串,包含appkey和file_link参数等。
  22.         // 新接入请使用4.0版本,已接入(默认2.0)如需维持现状,请注释掉该参数设置。
  23.         // 设置是否输出词信息,默认为false,开启时需要设置version为4.0。
  24.         $taskArr = array(self::KEY_APP_KEY => $appKey, self::KEY_FILE_LINK => $fileLink, self::KEY_VERSION => "4.0", self::KEY_ENABLE_WORDS => FALSE);
  25.         $task = json_encode($taskArr);
  26.         print $task . "\n";
  27.         try {
  28.             // 提交请求,返回服务端的响应。
  29.             $submitTaskResponse = AlibabaCloud::nlsFiletrans()
  30.                                               ->v20180817()
  31.                                               ->submitTask()
  32.                                               ->withTask($task)
  33.                                               ->request();
  34.             print $submitTaskResponse . "\n";
  35.             // 获取录音文件识别请求任务的ID,以供识别结果查询使用。
  36.             $taskId = NULL;
  37.             $statusText = $submitTaskResponse[self::KEY_STATUS_TEXT];
  38.             if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
  39.                 $taskId = $submitTaskResponse[self::KEY_TASK_ID];
  40.             }
  41.             return $taskId;
  42.         } catch (ClientException $exception) {
  43.             // 获取错误消息
  44.             print_r($exception->getErrorMessage());
  45.         } catch (ServerException $exception) {
  46.             // 获取错误消息
  47.             print_r($exception->getErrorMessage());
  48.         }
  49.     }
  50.     function getFileTransResult($taskId) {
  51.         $result = NULL;
  52.         while (TRUE) {
  53.             try {
  54.                 $getResultResponse = AlibabaCloud::nlsFiletrans()
  55.                                                  ->v20180817()
  56.                                                  ->getTaskResult()
  57.                                                  ->withTaskId($taskId)
  58.                                                  ->request();
  59.                 print "识别查询结果: " . $getResultResponse . "\n";
  60.                 $statusText = $getResultResponse[self::KEY_STATUS_TEXT];
  61.                 if (strcmp(self::STATUS_RUNNING, $statusText) == 0 || strcmp(self::STATUS_QUEUEING, $statusText) == 0) {
  62.                     // 继续轮询
  63.                     sleep(10);
  64.                 }
  65.                 else {
  66.                     if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
  67.                         $result = $getResultResponse;
  68.                     }
  69.                     // 退出轮询
  70.                     break;
  71.                 }
  72.             } catch (ClientException $exception) {
  73.                 // 获取错误消息
  74.                 print_r($exception->getErrorMessage());
  75.             } catch (ServerException $exception) {
  76.                 // 获取错误消息
  77.                 print_r($exception->getErrorMessage());
  78.             }
  79.         }
  80.         return $result;
  81.     }
  82. }
  83. $accessKeyId = "您的AccessKey Id";
  84. $accessKeySecret = "您的AccessKey Secret";
  85. $appKey = "您的appkey";
  86. $fileLink = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
  87. /**
  88.   * 第一步:设置一个全局客户端。
  89.   * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
  90. */
  91. AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
  92.             ->regionId("cn-shanghai")
  93.             ->asGlobalClient();
  94. $fileTrans = new NLSFileTrans();
  95. /**
  96.   *  第二步:提交录音文件识别请求,获取任务ID,用于后续的识别结果轮询。
  97. */
  98. $taskId = $fileTrans->submitFileTransRequest($appKey, $fileLink);
  99. if ($taskId != NULL) {
  100.     print "录音文件识别请求成功,task_id: " . $taskId . "\n";
  101. }
  102. else {
  103.     print "录音文件识别请求失败!";
  104.     return ;
  105. }
  106. /**
  107.   * 第三步:根据任务ID轮询识别结果。
  108. */
  109. $result = $fileTrans->getFileTransResult($taskId);
  110. if ($result != NULL) {
  111.     print "录音文件识别结果查询成功: " . $result . "\n";
  112. }
  113. else {
  114.     print "录音文件识别结果查询失败!";
  115. }
复制代码
以上实例为PHPSDK2.0(openapi-sdk-php)

回复

使用道具 举报

 楼主| admin 发表于 2023-2-17 20:05:08 | 显示全部楼层
  1. <?php

  2. namespace App\Helpers\Utils\Alibaba;

  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. use Illuminate\Support\Facades\Log;

  7. class NLSFileTrans {
  8.     // 请求参数
  9.     private const KEY_APP_KEY = "appkey";
  10.     private const KEY_FILE_LINK = "file_link";
  11.     private const KEY_VERSION = "version";
  12.     private const KEY_ENABLE_WORDS = "enable_words";
  13.     // 响应参数
  14.     private const KEY_TASK_ID = "TaskId";
  15.     private const KEY_STATUS_TEXT = "StatusText";
  16.     private const KEY_RESULT = "Result";
  17.     // 状态值
  18.     private const STATUS_SUCCESS = "SUCCESS";
  19.     private const STATUS_RUNNING = "RUNNING";
  20.     private const STATUS_QUEUEING = "QUEUEING";

  21.     public function submitFileTransRequest(string $appKey, $fileLink) {
  22.         // 获取task JSON字符串,包含appkey和file_link参数等。
  23.         // 新接入请使用4.0版本,已接入(默认2.0)如需维持现状,请注释掉该参数设置。
  24.         // 设置是否输出词信息,默认为false,开启时需要设置version为4.0。
  25.         $taskArr = array(
  26.             self::KEY_APP_KEY => $appKey,
  27.             self::KEY_FILE_LINK => $fileLink,
  28.             self::KEY_VERSION => "4.0",
  29.             self::KEY_ENABLE_WORDS => FALSE,
  30.             // @ref: https://help.aliyun.com/document_detail/90727.html#sectiondiv-qto-pl7-lvd
  31.             // 检查实际语音的采样率和控制台上Appkey绑定的ASR模型采样率是否一致
  32.             "enable_sample_rate_adaptive" => true,
  33.         );
  34.         $task = json_encode($taskArr);
  35.         Log::debug($task);

  36.         // 提交请求,返回服务端的响应。
  37.         $submitTaskResponse = AlibabaCloud::nlsFiletrans()
  38.             ->v20180817()
  39.             ->submitTask()
  40.             ->withTask($task)
  41.             ->request();
  42.         Log::info($submitTaskResponse);
  43.         // 获取录音文件识别请求任务的ID,以供识别结果查询使用。
  44.         $taskId = NULL;
  45.         $statusText = $submitTaskResponse[self::KEY_STATUS_TEXT];
  46.         if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
  47.             $taskId = $submitTaskResponse[self::KEY_TASK_ID];
  48.         }
  49.         return $taskId;

  50.     }

  51.     public function getFileTransResult($taskId) {
  52.         $result = NULL;
  53.         try {
  54.             $getResultResponse = AlibabaCloud::nlsFiletrans()
  55.                 ->v20180817()
  56.                 ->getTaskResult()
  57.                 ->withTaskId($taskId)
  58.                 ->request();
  59.             Log::notice("识别查询结果: " . json_encode($getResultResponse));

  60.             // $statusText = $getResultResponse[self::KEY_STATUS_TEXT];
  61.             // if (strcmp(self::STATUS_RUNNING, $statusText) == 0 || strcmp(self::STATUS_QUEUEING, $statusText) == 0) {}
  62.             // else {if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {$result = $getResultResponse;}}
  63.             $result = $getResultResponse;
  64.         } catch (ClientException $exception) {
  65.             // 获取错误消息
  66.             print_r($exception->getErrorMessage());
  67.         } catch (ServerException $exception) {
  68.             // 获取错误消息
  69.             print_r($exception->getErrorMessage());
  70.         }
  71.         return $result;
  72.     }
  73. }
复制代码


回复

使用道具 举报

 楼主| admin 发表于 2023-2-17 20:05:51 | 显示全部楼层
  1. <?php

  2. namespace App\Services;

  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. use App\Enums\ErrorCode;
  7. use App\Helpers\Utils\Alibaba\NLSFileTrans;
  8. use App\Helpers\Utils\Alibaba\OSS;
  9. use App\Models\Work;
  10. use Spatie\Permission\Exceptions\UnauthorizedException;

  11. class ApiService
  12. {
  13.     /**
  14.      * 提交录音文件识别请求,获取任务ID
  15.      * @param string $fileLink
  16.      * @return array
  17.      */
  18.     public function asrCreateTask(string $fileLink) {
  19.         $accessKeyId = config('constant.alibaba_access_key_id');
  20.         $accessKeySecret = config('constant.alibaba_access_key_secret');
  21.         $appKey = config('constant.alibaba_app_key');

  22.         /**
  23.          * 第一步:设置一个全局客户端。
  24.          * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
  25.          */
  26.         AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
  27.             ->regionId("cn-shanghai")
  28.             ->asGlobalClient();

  29.         $fileTrans = new NLSFileTrans();
  30.         /**
  31.          * @var $appKeyId string
  32.          * @ref: https://nls-portal.console.aliyun.com/applist 我的所有项目(不是access key)
  33.          * 确认开通了asr+tts服务
  34.          * https://nls-portal.console.aliyun.com/
  35.          */
  36.         try {
  37.             $taskId = $fileTrans->submitFileTransRequest($appKey, $fileLink);
  38.             if ($taskId != NULL) {
  39.                 $msg = "录音文件识别请求成功";
  40.                 return ['message' => $msg, 'code' => ErrorCode::OK, 'result' => ['task_id'=>$taskId], 'time'=>time()];
  41.             }
  42.         } catch (ClientException $e) {
  43.             // 获取错误消息
  44.             return ['message' => "failed", 'code'=> $e->getErrorCode(), 'error'=>$e->getErrorMessage()];
  45.         } catch (ServerException $e) {
  46.             return ['message' => "failed", 'code'=> $e->getErrorCode(), 'error'=>$e->getErrorMessage()];
  47.         }
  48.         return ['message'=>"failed", 'code'=> ErrorCode::API_ERROR, 'error'=>"语音识别任务创建失败"];
  49.     }

  50.     /**
  51.      * 异步查询ASR任务结果
  52.      * @param string $taskId
  53.      * @return array
  54.      * @throws ClientException
  55.      */
  56.     public function asrQuery(string $taskId) {
  57.         $accessKeyId = config('constant.alibaba_access_key_id');
  58.         $accessKeySecret = config('constant.alibaba_access_key_secret');
  59.         /**
  60.          * 第一步:设置一个全局客户端。
  61.          * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
  62.          */
  63.         AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
  64.             ->regionId("cn-shanghai")
  65.             ->asGlobalClient();

  66.         $fileTrans = new NLSFileTrans();
  67.         /**
  68.          * 第三步:根据任务ID轮询识别结果。
  69.          * @var $result \AlibabaCloud\Client\Result\Result
  70.          */
  71.         $result = $fileTrans->getFileTransResult($taskId);
  72.         if (is_null($result)) {
  73.             return ['message'=>"failed", 'code'=> ErrorCode::API_ERROR, 'error'=>"录音文件识别结果查询失败!",'time'=>time()];
  74.         }
  75.         /** @var $s string JSON string */
  76.         $s = $result->toJson();
  77.         header("Content-Type: application/json");
  78.         echo $s;
  79.         exit(0);
  80.     }

  81.     public function fetchWork(int $workId, int $memberId, string $downloadType = 'wav') {
  82.         /** @var $work Work */
  83.         $work = Work::find($workId);
  84.         if (empty($work)) {
  85.             throw new \InvalidArgumentException("作品ID不存在", ErrorCode::PARAM_ERROR);
  86.         }
  87.         if (0 != $work->getMemberId()-$memberId) {
  88.             throw new UnauthorizedException(ErrorCode::PERMISSION_DENIED, "只能下载自己的作品");
  89.         }
  90.         return $work;
  91.     }

  92.     public function upload(string $path, string $ext, string $bucket) {
  93.         $oss = new OSS();
  94.         $filename = md5_file($path);

  95.         $uri = sprintf("%s/%s.%s", date("Y-m-d", time()), $filename, $ext);
  96.         $oss->bucket($bucket)->upload($uri, $path, $bucket);
  97.         return "https://".$bucket.".".OSS::END_POINT."/".$uri;
  98.     }
  99. }
复制代码


回复

使用道具 举报

 楼主| admin 发表于 2023-7-24 23:50:11 | 显示全部楼层
  1. <?php
  2. namespace app\index\loglic;
  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. class AliRecord
  7. {
  8.     private $error = '';
  9.    
  10.     //获取错误信息
  11.     public function getError()
  12.     {
  13.         return $this->error;
  14.     }

  15.     //获取任务ID
  16.     function submitFileTransRequest($fileLink='')
  17.     {
  18.         AlibabaCloud::accessKeyClient(config('apis.aliyun_key'), config('apis.aliyun_secret'))->regionId(config('apis.aliyun_region'))->asGlobalClient();

  19.         $task = json_encode([
  20.             "appkey"         => config('trans.aliyun_appkey'),
  21.             "file_link"      => $fileLink,
  22.             "version"        => "4.0",
  23.             "enable_words"   => FALSE,
  24.             "enable_sample_rate_adaptive" => TRUE
  25.         ]);

  26.         $taskId = NULL;

  27.         try {
  28.             // 提交请求,返回服务端的响应。
  29.             $result = AlibabaCloud::nlsFiletrans()->v20180817()->submitTask()->withTask($task)->request()->toArray();
  30.             //判断结果
  31.             if($result['StatusText'] == 'SUCCESS'){
  32.                 $taskId = $result['TaskId'];
  33.             }else{
  34.                 $this->error = $result['StatusText'].$result['StatusCode'];
  35.             }
  36.         } catch (ClientException $exception) {
  37.             $this->error = $exception->getErrorMessage();
  38.         } catch (ServerException $exception) {
  39.             $this->error = $exception->getErrorMessage();
  40.         }

  41.         return $taskId;
  42.     }

  43.     //查询识别结果
  44.     function getFileTransResult($taskId='')
  45.     {
  46.         AlibabaCloud::accessKeyClient(config('apis.aliyun_key'), config('apis.aliyun_secret'))->regionId(config('apis.aliyun_region'))->asGlobalClient();

  47.         $result = NULL;

  48.         while(TRUE){
  49.             try{
  50.                 $response = AlibabaCloud::nlsFiletrans()->v20180817()->getTaskResult()->withTaskId($taskId)->request();
  51.                 $response = $response->toArray();
  52.                 //转换状态
  53.                 $statusText = $response['StatusText'];
  54.                 if(in_array($statusText,['RUNNING','QUEUEING'])){
  55.                     sleep(5);
  56.                 }else{
  57.                     //是否成功
  58.                     if($statusText == 'SUCCESS'){
  59.                         $result = $response['Result']['Sentences'];
  60.                     }else{
  61.                         $this->error = $statusText;
  62.                     }
  63.                     //退出轮询
  64.                     break;
  65.                 }
  66.             }catch(ClientException $exception){
  67.                 $this->error = $exception->getErrorMessage();
  68.             }catch(ServerException $exception){
  69.                 $this->error = $exception->getErrorMessage();
  70.             }
  71.         }

  72.         return $result;
  73.     }
  74. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

QQ|Archiver|手机版|小黑屋|信息共享网

GMT+8, 2024-5-14 04:39 , Processed in 0.085184 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表