PHP Demo

更新时间:
复制 MD 格式

This topic describes how to use the PHP SDK for Alibaba Cloud Voice Service, including SDK installation and code examples.

Prerequisites

  • Before you use the SDK, you should read the API reference.

  • You have activated Intelligent Speech Interaction and obtained an AccessKey ID and an AccessKey secret. For more information, see Get started.

Note
  • The PHP examples in this topic are based on the new Alibaba Cloud SDK for PHP. If you have integrated an earlier version of the Alibaba Cloud SDK for PHP (aliyun-openapi-php-sdk), you can continue to use it. However, we recommend that you update to the new SDK.

  • The PHP demo of the recording file recognition service is updated based only on the latest version of Alibaba Cloud SDK for PHP.

SDK description

  • In the PHP demo of the recording file recognition service, Alibaba Cloud SDK for PHP is used to send Alibaba Cloud pctowap open platform (POP) API requests in a remote procedure call (RPC) style. You can send a recording file recognition request and query the recording file recognition result.

  • For more information about the Alibaba Cloud SDK for PHP, see PHP SDK.

Important

Alibaba Cloud SDK for PHP supports PHP 5.5.0 or later.

SDK installation

For more information, see Install Alibaba Cloud SDK for PHP.

Call procedure

  1. Create a global client.

  2. Create a recording file recognition request and set request parameters. Send the recording file recognition request and process the response that the server returns to obtain the task ID.

  3. Poll the recognition result based on the task ID.

Sample code

  • Download nls-sample-16k.wav. The recording file is in the Pulse-Code Modulation (PCM) format with a sample rate of 16000 Hz. This sample uses the general-purpose model, which is set in the console. If you use a different recording file, you must specify its encoding format and sample rate, and select the corresponding model in the console. For more information about setting models, see Manage projects.

  • Before you call the API, configure environment variables for your access credentials. The environment variables are ALIYUN_AK_ID for your AccessKey ID, ALIYUN_AK_SECRET for your AccessKey secret, and NLS_APP_KEY for the AppKey of Intelligent Speech Interaction.

<?php
require __DIR__ . '/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class NLSFileTrans {
    // Request parameters
    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";
    // Response parameters
    private const KEY_TASK_ID = "TaskId";
    private const KEY_STATUS_TEXT = "StatusText";
    private const KEY_RESULT = "Result";
    // Status values
    private const STATUS_SUCCESS = "SUCCESS";
    private const STATUS_RUNNING = "RUNNING";
    private const STATUS_QUEUEING = "QUEUEING";
    function submitFileTransRequest($appKey, $fileLink) {
        // Obtain the task JSON string, which includes parameters such as appkey and file_link.
        // If you are a new user, use version 4.0. If you are an existing user (default is 2.0) and want to maintain the current state, comment out this parameter setting.
        // Specify whether to output word-level information. The default value is false. To enable this feature, you must set the version to 4.0.
        $taskArr = array(self::KEY_APP_KEY => $appKey, self::KEY_FILE_LINK => $fileLink, self::KEY_VERSION => "4.0", self::KEY_ENABLE_WORDS => FALSE);
        $task = json_encode($taskArr);
        print $task . "\n";
        try {
            // Submit the request and receive the response from the server.
            $submitTaskResponse = AlibabaCloud::nlsFiletrans()
                                              ->v20180817()
                                              ->submitTask()
                                              ->withTask($task)
                                              ->request();
            print $submitTaskResponse . "\n";
            // Obtain the ID of the recording file recognition task. This ID is used to query the recognition result.
            $taskId = NULL;
            $statusText = $submitTaskResponse[self::KEY_STATUS_TEXT];
            if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
                $taskId = $submitTaskResponse[self::KEY_TASK_ID];
            }
            return $taskId;
        } catch (ClientException $exception) {
            // Obtain the error message.
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            // Obtain the error message.
            print_r($exception->getErrorMessage());
        }
    }
    function getFileTransResult($taskId) {
        $result = NULL;
        while (TRUE) {
            try {
                $getResultResponse = AlibabaCloud::nlsFiletrans()
                                                 ->v20180817()
                                                 ->getTaskResult()
                                                 ->withTaskId($taskId)
                                                 ->request();
                print "Recognition query result: " . $getResultResponse . "\n";
                $statusText = $getResultResponse[self::KEY_STATUS_TEXT];
                if (strcmp(self::STATUS_RUNNING, $statusText) == 0 || strcmp(self::STATUS_QUEUEING, $statusText) == 0) {
                    // Continue polling.
                    sleep(10);
                }
                else {
                    if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
                        $result = $getResultResponse;
                    }
                    // Exit polling.
                    break;
                }
            } catch (ClientException $exception) {
                // Obtain the error message.
                print_r($exception->getErrorMessage());
            } catch (ServerException $exception) {
                // Obtain the error message.
                print_r($exception->getErrorMessage());
            }
        }
        return $result;
    }
}
$accessKeyId = getenv('ALIYUN_AK_ID');
$accessKeySecret = getenv('ALIYUN_AK_SECRET');
$appKey = getenv('NLS_APP_KEY');
$fileLink = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
/**
  * Step 1: Set a global client.
  * Use the AccessKey ID and AccessKey secret of an Alibaba Cloud RAM user for authentication.
 */
AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId("cn-shanghai")
            ->asGlobalClient();
$fileTrans = new NLSFileTrans();
/**
  *  Step 2: Submit a recording file recognition request to obtain the task ID for subsequent polling of the recognition result.
 */
$taskId = $fileTrans->submitFileTransRequest($appKey, $fileLink);
if ($taskId != NULL) {
    print "Recording file recognition request submitted successfully. task_id: " . $taskId . "\n";
}
else {
    print "Failed to submit the recording file recognition request!";
    return ;
}
/**
  * Step 3: Poll for the recognition result based on the task ID.
 */
$result = $fileTrans->getFileTransResult($taskId);
if ($result != NULL) {
    print "Recording file recognition result queried successfully: " . $result . "\n";
}
else {
    print "Failed to query the recording file recognition result!";
}