本文由簡體中文內容自動轉碼而成。阿里雲不保證此自動轉碼的準確性、完整性及時效性。本文内容請以簡體中文版本為準。

RESTful API

更新時間:2024-12-18 12:16

一句話識別RESTful API支援以HTTPS POST方式整段上傳不超過一分鐘的語音檔案。識別結果將以JSON格式在請求響應中一次性返回,開發人員需要保證在識別結果返回之前串連不中斷。

功能介紹

  • 支援的輸入格式:單聲道(mono)、16 bit採樣位元,包括PCM、PCM編碼的WAV、OGG封裝的OPUS、OGG封裝的SPEEX、AMR、MP3、AAC。

  • 音頻採樣率:8000 Hz、16000 Hz。

  • 支援設定返回結果:是否在後處理中添加標點,是否將中文數字轉為阿拉伯數字輸出。

  • 支援控制台設定項目熱詞、定製語言模型。

  • 支援多種語言識別,可在控制台編輯專案進行模型配置,詳情請參見Manage projects

前提條件

互動流程

用戶端向服務端發送帶有音頻資料的HTTPS RESTful POST請求,服務端返回帶有識別結果的HTTPS響應。

互動流程圖

說明

服務端的響應除了音頻流之外,都會在返回資訊的header包含本次識別任務的task_id參數,是本次請求的唯一標識。

服務地址

訪問類型

說明

URL

Host

訪問類型

說明

URL

Host

外網訪問(預設上海地區)

所有伺服器均可使用外網訪問URL。

  • 上海:https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr

  • 北京:https://nls-gateway-cn-beijing.aliyuncs.com/stream/v1/asr

  • 深圳:https://nls-gateway-cn-shenzhen.aliyuncs.com/stream/v1/asr

  • 上海:nls-gateway-cn-shanghai.aliyuncs.com

  • 北京:nls-gateway-cn-beijing.aliyuncs.com

  • 深圳:nls-gateway-cn-shenzhen.aliyuncs.com

ECS內網訪問

使用阿里雲上海、北京、深圳ECS(即ECS地區為華東2(上海)、華北2(北京)、華南1(深圳)),可使用內網訪問URL。 ECS的傳統網路不能訪問AnyTunnel,即不能在內網訪問Voice Messaging Service;如果希望使用AnyTunnel,需要建立專用網路在其內部訪問。

說明

  • 使用內網訪問方式,將不產生ECS執行個體的公網流量費用。

  • 關於ECS的網路類型請參見網路類型

  • 上海:http://nls-gateway-cn-shanghai-internal.aliyuncs.com/stream/v1/asr

  • 北京:http://nls-gateway-cn-beijing-internal.aliyuncs.com/stream/v1/asr

  • 深圳:http://nls-gateway-cn-shenzhen-internal.aliyuncs.com/stream/v1/asr

  • 上海:nls-gateway-cn-shanghai-internal.aliyuncs.com

  • 北京:nls-gateway-cn-beijing-internal.aliyuncs.com

  • 深圳:nls-gateway-cn-shenzhen-internal.aliyuncs.com

重要

以下將以使用外網訪問URL的方式進行介紹。如果您使用阿里雲上海、北京、深圳ECS,並需要通過內網訪問URL,則使用HTTP協議,並替換外網訪問的URL和Host。

輸入音頻

上傳二進位音頻流

一句話識別請求HTTPS報文執行個體。

POST /stream/v1/asr?appkey=23f5****&format=pcm&sample_rate=16000&enable_punctuation_prediction=true&enable_inverse_text_normalization=true HTTP/1.1
X-NLS-Token: 450372e4279bcc2b3c793****
Content-type: application/octet-stream
Content-Length: 94616
Host: nls-gateway-cn-shanghai.aliyuncs.com

[audio data]

一個完整的一句話識別RESTful API請求需包含以下要素:HTTPS請求行、HTTPS要求標頭部和HTTPS請求體。

  • HTTPS請求行

    HTTPS請求行指定了URL請求參數,由URL和請求參數組成的完整請求連結如下:

    https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr?appkey=Yu1******uncS&format=pcm&sample_rate=16000&vocabulary_id=a17******d6b&customization_id=abd******ed8&enable_punctuation_prediction=true&enable_inverse_text_normalization=true&enable_voice_detection=true
    • URL

      協議

      URL

      方法

      協議

      URL

      方法

      HTTP/1.1

      nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr

      POST

    • 請求參數

      參數

      類型

      是否必選

      描述

      參數

      類型

      是否必選

      描述

      appkey

      String

      應用Appkey。

      擷取Appkey請前往控制台

      format

      String

      音頻格式,包括PCM、WAV、OPUS、SPEEX、AMR、MP3、AAC。

      sample_rate

      Integer

      音頻採樣率。取值:16000 Hz、8000 Hz。預設值:16000 Hz。

      vocabulary_id

      String

      添加熱詞表ID。預設:不添加。

      customization_id

      String

      添加自學習模型ID。預設:不添加。

      enable_punctuation_prediction

      Boolean

      是否在後處理中添加標點,預設值:False(關閉。

      enable_inverse_text_normalization

      Boolean

      ITN(逆文本inverse text normalization)中文數字轉換阿拉伯數字。設定為True時,中文數字將轉為阿拉伯數字輸出,預設值:False。

      enable_voice_detection

      Boolean

      是否啟動語音檢測。開啟後能夠識別出一段音頻中有效語音的開始和結束,剔除噪音資料。預設值:False(不開啟)。 

      disfluency

      Boolean

      過濾語氣詞,即聲音順滑,預設值:False(關閉)。

  • HTTPS要求標頭部

    HTTPS要求標頭部由“關鍵字-值”對組成,每行一對,關鍵字和值用英文冒號“:”分隔,設定內容如下:

    名稱

    類型

    是否必選

    描述

    名稱

    類型

    是否必選

    描述

    X-NLS-Token

    String

    服務鑒權Token。

    Content-type

    String

    取值“application/octet-stream”,表明HTTPS請求體的資料為二進位流。

    Content-Length

    long

    HTTPS請求體中請求資料的長度,即音頻檔案的長度。

    Host

    String

    取值“nls-gateway-cn-shanghai.aliyuncs.com”,為HTTPS請求的伺服器網域名稱。

  • HTTPS請求體

    HTTPS請求體傳入的是二進位音頻資料,因此在HTTPS要求標頭部中的Content-Type必須設定為application/octet-stream

使用音頻檔案連結

一句話識別請求HTTPS報文執行個體。

POST /stream/v1/asr?appkey=23f5****&format=pcm&sample_rate=16000&enable_punctuation_prediction=true&enable_inverse_text_normalization=true&audio_address=your-audio-url HTTP/1.1
X-NLS-Token: 450372e4279bcc2b3c793****
Host: nls-gateway-cn-shanghai.aliyuncs.com

一個完整的一句話識別RESTful API請求需包含以下要素:HTTPS請求行、HTTPS要求標頭部和HTTPS請求體。

  • HTTPS請求行

    HTTPS請求行指定了URL請求參數,由URL和請求參數組成的完整請求連結如下:

    https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr?appkey=Yu1******uncS&format=pcm&sample_rate=16000&vocabulary_id=a17******d6b&customization_id=abd******ed8&enable_punctuation_prediction=true&enable_inverse_text_normalization=true&enable_voice_detection=true&audio_address=your-audio-url
    • URL

      協議

      URL

      方法

      協議

      URL

      方法

      HTTP/1.1

      nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr

      POST

    • 請求參數

      參數

      類型

      是否必選

      描述

      參數

      類型

      是否必選

      描述

      appkey

      String

      應用Appkey。

      擷取Appkey請前往控制台

      format

      String

      音頻格式,包括PCM、WAV、OPUS、SPEEX、AMR、MP3、AAC。

      sample_rate

      Integer

      音頻採樣率。取值:16000 Hz、8000 Hz。預設值:16000 Hz。

      vocabulary_id

      String

      添加熱詞表ID。預設:不添加。

      customization_id

      String

      添加自學習模型ID。預設:不添加。

      enable_punctuation_prediction

      Boolean

      是否在後處理中添加標點,預設值:False(關閉。

      enable_inverse_text_normalization

      Boolean

      ITN(逆文本inverse text normalization)中文數字轉換阿拉伯數字。設定為True時,中文數字將轉為阿拉伯數字輸出,預設值:False。

      enable_voice_detection

      Boolean

      是否啟動語音檢測。開啟後能夠識別出一段音頻中有效語音的開始和結束,剔除噪音資料。預設值:False(不開啟)。 

      disfluency

      Boolean

      過濾語氣詞,即聲音順滑,預設值:False(關閉)。

      audio_address

      String

      可通過公網訪問的音頻檔案下載連結。推薦使用阿里雲OSS,具體請參見通過OSS如何擷取訪問URL

  • HTTPS要求標頭部

    HTTPS要求標頭部由“關鍵字-值”對組成,每行一對,關鍵字和值用英文冒號“:”分隔,設定內容如下:

    名稱

    類型

    是否必選

    描述

    名稱

    類型

    是否必選

    描述

    X-NLS-Token

    String

    服務鑒權Token。

    Host

    String

    取值“nls-gateway-cn-shanghai.aliyuncs.com”,為HTTPS請求的伺服器網域名稱。

響應結果

發送上傳音訊HTTPS請求後,會收到服務端的響應,識別結果以JSON字串的形式儲存在響應結果中。

  • 成功響應

    {
        "task_id": "cf7b0c5339244ee29cd4e43fb97f****",
        "result": "北京的天氣。",
        "status":20000000,
        "message":"SUCCESS"
    }
  • 失敗響應

    以鑒權token無效為例:

    {
        "task_id": "8bae3613dfc54ebfa811a17d8a7a****",
        "result": "",
        "status": 40000001,
        "message": "Gateway:ACCESS_DENIED:The token 'c0c1e860f3*******de8091c68a' is invalid!"
    }

    參數

    類型

    描述

    參數

    類型

    描述

    task_id

    String

    32位任務ID。請您記錄該值,以便排查錯誤。

    result

    String

    語音辨識結果。

    status

    Integer

    服務狀態代碼。

    message

    String

    服務狀態原因。

服務狀態代碼

服務狀態代碼

服務狀態原因

解決方案

服務狀態代碼

服務狀態原因

解決方案

20000000

請求成功

無。

40000000

預設的用戶端錯誤碼

檢查對應的錯誤訊息。

40000001

身份認證失敗

檢查使用的令牌是否正確、是否到期。

40000002

無效的訊息

檢查發送的訊息是否符合要求。

40000003

無效的參數

檢查參數值設定是否合理。

40000004

空閑逾時

確認是否長時間沒有發送資料到服務端。

40000005

請求數量過多

檢查是否超過了並發串連數或者每秒鐘請求數。

40000010

新使用者免費試用3個月已到期

繼續使用需要付費商用,請前往控制台,在服務管理與開通頁面,單擊目標服務右側的升級為商用版,進行付費使用。

41010101

不支援的採樣率

檢查代碼中設定的採樣率參數(8000/16000)與管控台上Appkey對應的模型(8k/16k)是否匹配。

50000000

預設的服務端錯誤

內部服務錯誤,需要用戶端進行重試。

50000001

內部GRPC調用錯誤

內部服務錯誤,需要用戶端進行重試。

快速測試

說明

音頻樣本WAV檔案,使用通用模型。若使用其他音頻檔案,請填入相應的編碼格式和採樣率,並在管控台設定對應的模型。

  1. 下載音頻檔案nls-sample-16k.wav

  2. 使用如下cURL命令列進行一句話識別的RESTful API測試。

    curl -X POST -H "X-NLS-Token: ${token}" https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr?appkey=${appkey} --data-binary @${audio_file}

    舉例如下:

    curl -X POST -H "X-NLS-Token: 4a036531cfdd****" https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr?appkey=tt43P2u**** --data-binary @./nls-sample-16k.wav

Java樣本

依賴檔案如下:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.1</version>
</dependency>

<!-- http://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

發送請求與響應:

import com.alibaba.fastjson.JSONPath;
import com.alibaba.nls.client.example.utils.HttpUtil;
import java.util.HashMap;
public class SpeechRecognizerRESTfulDemo {
    private String accessToken;
    private String appkey;

    public SpeechRecognizerRESTfulDemo(String appkey, String token) {
        this.appkey = appkey;
        this.accessToken = token;
    }

    public void process(String fileName, String format, int sampleRate,
                        boolean enablePunctuationPrediction,
                        boolean enableInverseTextNormalization,
                        boolean enableVoiceDetection) {

        /**
         * 設定HTTPS RESTful POST請求:
         * 1.使用HTTPS協議。
         * 2.語音辨識服務網域名稱:nls-gateway-cn-shanghai.aliyuncs.com。
         * 3.語音辨識介面請求路徑:/stream/v1/asr。
         * 4.設定必選請求參數:appkey、format、sample_rate。
         * 5.設定可選請求參數:enable_punctuation_prediction、enable_inverse_text_normalization、enable_voice_detection。
         */
        String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
        String request = url;
        request = request + "?appkey=" + appkey;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;
        if (enablePunctuationPrediction) {
            request = request + "&enable_punctuation_prediction=" + true;
        }
        if (enableInverseTextNormalization) {
            request = request + "&enable_inverse_text_normalization=" + true;
        }
        if (enableVoiceDetection) {
            request = request + "&enable_voice_detection=" + true;
        }

        System.out.println("Request: " + request);

        /**
         * 設定HTTPS頭部欄位:
         * 1.鑒權參數。
         * 2.Content-Type:application/octet-stream。
         */
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("X-NLS-Token", this.accessToken);
        headers.put("Content-Type", "application/octet-stream");

        /**
         * 發送HTTPS POST請求,返回服務端的響應。
         */
        String response = HttpUtil.sendPostFile(request, headers, fileName);

        if (response != null) {
            System.out.println("Response: " + response);
            String result = JSONPath.read(response, "result").toString();
            System.out.println("識別結果:" + result);
        }
        else {
            System.err.println("識別失敗!");
        }

    }

    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("SpeechRecognizerRESTfulDemo need params: <token> <app-key>");
            System.exit(-1);
        }

        String token = args[0];
        String appkey = args[1];

        SpeechRecognizerRESTfulDemo demo = new SpeechRecognizerRESTfulDemo(appkey, token);

        String fileName = SpeechRecognizerRESTfulDemo.class.getClassLoader().getResource("./nls-sample-16k.wav").getPath();
        String format = "pcm";
        int sampleRate = 16000;
        boolean enablePunctuationPrediction = true;
        boolean enableInverseTextNormalization = true;
        boolean enableVoiceDetection = false;

        demo.process(fileName, format, sampleRate, enablePunctuationPrediction, enableInverseTextNormalization, enableVoiceDetection);
    }
}

其中,HttpUtils類如下:

import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    private static String getResponseWithTimeout(Request q) {
        String ret = null;

        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient client = httpBuilder.connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        try {
            Response s = client.newCall(q).execute();
            ret = s.body().string();
            s.close();
        } catch (SocketTimeoutException e) {
            ret = null;
            System.err.println("get result timeout");
        } catch (IOException e) {
            System.err.println("get result error " + e.getMessage());
        }

        return ret;
    }

    public static String sendPostFile(String url, HashMap<String, String> headers, String fileName) {
        RequestBody body;

        File file = new File(fileName);
        if (!file.isFile()) {
            System.err.println("The filePath is not a file: " + fileName);
            return null;
        } else {
            body = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        }

        Headers.Builder hb = new Headers.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                hb.add(entry.getKey(), entry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .headers(hb.build())
                .post(body)
                .build();

        return getResponseWithTimeout(request);
    }

    public static String sendPostData(String url, HashMap<String, String> headers, byte[] data) {
        RequestBody body;

        if (data.length == 0) {
            System.err.println("The send data is empty.");
            return null;
        } else {
            body = RequestBody.create(MediaType.parse("application/octet-stream"), data);
        }

        Headers.Builder hb = new Headers.Builder();
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                hb.add(entry.getKey(), entry.getValue());
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .headers(hb.build())
                .post(body)
                .build();

        return getResponseWithTimeout(request);
    }
}

C++樣本

C++樣本使用第三方函數庫curl處理HTTPS請求和響應。下載curl庫和Demo檔案

目錄說明如下所示。

檔案/檔案夾

說明

檔案/檔案夾

說明

CMakeLists.txt

樣本工程的CMakeList檔案。

demo

其中的restfulAsrDemo.cpp是一句話識別RESTful API Demo。

include

其中curl檔案夾是curl庫標頭檔目錄。

lib

包含curl動態庫,版本為curl-7.60。根據平台不同選如下版本:

  • Linux:Glibc 2.5、Gcc 4/Gcc 5。

  • Windows:VS2013、VS2015。

readme.txt

說明。

release.log

更新記錄。

version

版本號碼。

build.sh

樣本編譯指令碼。

編譯運行操作步驟:

假設樣本檔案已解壓至path/to路徑下,在Linux終端依次執行如下命令編譯運行程式。

  • 支援Cmake:

    1. 確認本地系統已安裝Cmake 2.4及以上版本。

    2. cd path/to/sdk/lib

    3. tar -zxvpf linux.tar.gz

    4. cd path/to/sdk

    5. ./build.sh

    6. cd path/to/sdk/demo

    7. ./restfulAsrDemo <your-token> <your-appkey>

  • 不支援Cmake:

    1. cd path/to/sdk/lib

    2. tar -zxvpf linux.tar.gz

    3. cd path/to/sdk/demo

    4. g++ -o restfulAsrDemo restfulAsrDemo.cpp -I path/to/sdk/include -L path/to/sdk/lib/linux -lssl -lcrypto -lcurl -D_GLIBCXX_USE_CXX11_ABI=0

    5. export LD_LIBRARY_PATH=path/to/sdk/lib/linux/

    6. ./restfulAsrDemo <your-token> <your-appkey>

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "curl/curl.h"

using namespace std;

#ifdef _WIN32
string UTF8ToGBK(const string& strUTF8) {
    int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
    unsigned short * wszGBK = new unsigned short[len + 1];
    memset(wszGBK, 0, len * 2 + 2);

    MultiByteToWideChar(CP_UTF8, 0, (char*)strUTF8.c_str(), -1, (wchar_t*)wszGBK, len);

    len = WideCharToMultiByte(CP_ACP, 0, (wchar_t*)wszGBK, -1, NULL, 0, NULL, NULL);

    char *szGBK = new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte(CP_ACP, 0, (wchar_t*)wszGBK, -1, szGBK, len, NULL, NULL);

    string strTemp(szGBK);
    delete[] szGBK;
    delete[] wszGBK;

    return strTemp;
}

#endif

/**
 * 一句話識別RESTful API HTTPS請求的響應回呼函數
 * 識別結果為JSON格式的字串
 */
size_t responseCallback(void* ptr, size_t size, size_t nmemb, void* userData) {
    string* srResult = (string*)userData;

    size_t len = size * nmemb;
    char *pBuf = (char*)ptr;
    string response = string(pBuf, pBuf + len);
#ifdef _WIN32
    response = UTF8ToGBK(response);
#endif
    cout << "current result: " << response << endl;

    *srResult += response;
    cout << "total result: " << *srResult << endl;

    return len;
}

int sendAsrRequest(const char* request, const char* token, const char* fileName, string* srResult) {
    CURL* curl = NULL;
    CURLcode res;

    /**
    * 讀取音頻檔案
    */
    ifstream fs;
    fs.open(fileName, ios::out | ios::binary);
    if (!fs.is_open()) {
        cerr << "The audio file is not exist!" << endl;
        return -1;
    }
    stringstream buffer;
    buffer << fs.rdbuf();
    string audioData(buffer.str());

    curl = curl_easy_init();
    if (curl == NULL) {
        return -1;
    }

    /**
    * 設定HTTPS請求行
    */
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, request);

    /**
    * 設定HTTPS要求標頭部
    */
    struct curl_slist* headers = NULL;
    // token
    string X_NLS_Token = "X-NLS-Token:";
    X_NLS_Token += token;
    headers = curl_slist_append(headers, X_NLS_Token.c_str());
    // Content-Type
    headers = curl_slist_append(headers, "Content-Type:application/octet-stream");
    // Content-Length
    string content_Length = "Content-Length:";
    ostringstream oss;
    oss << content_Length << audioData.length();
    content_Length = oss.str();
    headers = curl_slist_append(headers, content_Length.c_str());

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    /**
    * 設定HTTPS請求資料
    */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, audioData.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, audioData.length());

    /**
    * 設定HTTPS請求的響應回呼函數
    */
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, srResult);

    /**
    * 發送HTTPS請求
    */
    res = curl_easy_perform(curl);

    // 釋放資源
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
        cerr << "curl_easy_perform failed: " << curl_easy_strerror(res) << endl;
        return -1;
    }

    return 0;
}

int process(const char* request, const char* token, const char* fileName) {
    // 全域只初始化一次
    curl_global_init(CURL_GLOBAL_ALL);

    string srResult = "";
    int ret = sendAsrRequest(request, token, fileName, &srResult);

    curl_global_cleanup();

    return ret;
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        cerr << "params is not valid. Usage: ./demo your_token your_appkey" << endl;
        return -1;
    }

    string token = argv[1];
    string appKey = argv[2];

    string url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
    string format = "pcm";
    int sampleRate = 16000;
    bool enablePunctuationPrediction = true;
    bool enableInverseTextNormalization = true;
    bool enableVoiceDetection = false;
    string fileName = "sample.pcm";

    /**
    * 設定RESTful請求參數
    */
    ostringstream oss;
    oss << url;
    oss << "?appkey=" << appKey;
    oss << "&format=" << format;
    oss << "&sample_rate=" << sampleRate;
    if (enablePunctuationPrediction) {
        oss << "&enable_punctuation_prediction=" << "true";
    }
    if (enableInverseTextNormalization) {
        oss << "&enable_inverse_text_normalization=" << "true";
    }
    if (enableVoiceDetection) {
        oss << "&enable_voice_detection=" << "true";
    }

    string request = oss.str();
    cout << "request: " << request << endl;

    process(request.c_str(), token.c_str(), fileName.c_str());

    return 0;
}

Python樣本

說明

Python 2.x請使用httplib模組;Python 3.x請使用http.client模組。採用RFC 3986規範進行urlencode編碼,Python 2.x請使用urllib模組的urllib.quote,Python 3.x請使用urllib.parse模組的urllib.parse.quote_plus。如果使用內網訪問URL,請使用HTTP協議,需要替換如下函數,將HTTPSConnection修改為:

如果使用內網訪問URL,請使用HTTP協議,需要替換如下函數,將HTTPSConnection修改為HTTPConnection:
 # Python 2.x 請使用httplib
 # conn = httplib.HTTPConnection(host)
 # Python 3.x 請使用http.client
 conn = http.client.HTTPConnection(host)
# -*- coding: UTF-8 -*-
# Python 2.x引入httplib模組
# import httplib
# Python 3.x引入http.client模組
import http.client

import json

def process(request, token, audioFile) :

    # 讀取音頻檔案
    with open(audioFile, mode = 'rb') as f:
        audioContent = f.read()

    host = 'nls-gateway-cn-shanghai.aliyuncs.com'

    # 設定HTTPS要求標頭部
    httpHeaders = {
        'X-NLS-Token': token,
        'Content-type': 'application/octet-stream',
        'Content-Length': len(audioContent)
        }

    # Python 2.x使用httplib
    # conn = httplib.HTTPSConnection(host)
    
    # Python 3.x使用http.client
    conn = http.client.HTTPSConnection(host)

    conn.request(method='POST', url=request, body=audioContent, headers=httpHeaders)

    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)

    body = response.read()
    try:
        print('Recognize response is:')
        body = json.loads(body)
        print(body)

        status = body['status']
        if status == 20000000 :
            result = body['result']
            print('Recognize result: ' + result)
        else :
            print('Recognizer failed!')

    except ValueError:
        print('The response is not json format string')

    conn.close()



appKey = '填入appkey'
token = '填入服務鑒權Token'

# 服務要求地址
url = 'https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr'

# 音頻檔案
audioFile = '/path/to/nls-sample-16k.wav'
format = 'pcm'
sampleRate = 16000
enablePunctuationPrediction  = True
enableInverseTextNormalization = True
enableVoiceDetection  = False

# 設定RESTful請求參數
request = url + '?appkey=' + appKey
request = request + '&format=' + format
request = request + '&sample_rate=' + str(sampleRate)

if enablePunctuationPrediction :
    request = request + '&enable_punctuation_prediction=' + 'true'

if enableInverseTextNormalization :
    request = request + '&enable_inverse_text_normalization=' + 'true'

if enableVoiceDetection :
    request = request + '&enable_voice_detection=' + 'true'

print('Request: ' + request)


process(request, token, audioFile)

PHP樣本

說明

PHP樣本中使用了cURL函數,要求PHP版本4.0.2以上,並且已安裝cURL擴充。

<?php

function process($token, $request, $audioFile) {
    /**
     * 讀取音頻檔案
     */
    $audioContent = file_get_contents($audioFile);
    if ($audioContent == FALSE) {
        print "The audio file is not exist!\n";
        return;
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 120);

    /**
     * 設定HTTPS請求行
     */
    curl_setopt($curl, CURLOPT_URL, $request);
    curl_setopt($curl, CURLOPT_POST,TRUE);

    /**
     * 設定HTTPS要求標頭部
     */
    $contentType = "application/octet-stream";
    $contentLength = strlen($audioContent);
    $headers = array(
        "X-NLS-Token:" . $token,
        "Content-type:" . $contentType,
        "Content-Length:" . strval($contentLength)
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    /**
     * 設定HTTPS請求資料
     */
    curl_setopt($curl, CURLOPT_POSTFIELDS, $audioContent);
    curl_setopt($curl, CURLOPT_NOBODY, FALSE);

    /**
     * 發送HTTPS請求
     */
    $returnData = curl_exec($curl);

    curl_close($curl);

    if ($returnData == FALSE) {
        print "curl_exec failed!\n";
        return;
    }

    print $returnData . "\n";

    $resultArr = json_decode($returnData, true);

    $status = $resultArr["status"];
    if ($status == 20000000) {
        $result = $resultArr["result"];
        print "The audio file recognized result: " . $result . "\n";
    }
    else {
        print "The audio file recognized failed.\n";
    }

}


$appkey = "填入appkey";
$token = "填入服務鑒權Token";

$url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
$audioFile = "/path/to/nls-sample-16k.wav";
$format = "pcm";
$sampleRate = 16000;
$enablePunctuationPrediction = TRUE;
$enableInverseTextNormalization = TRUE;
$enableVoiceDetection = FALSE;

/**
 * 設定RESTful請求參數
 */
$request = $url;
$request = $request . "?appkey=" . $appkey;
$request = $request . "&format=" . $format;
$request = $request . "&sample_rate=" . strval($sampleRate);
if ($enablePunctuationPrediction) {
    $request = $request . "&enable_punctuation_prediction=" . "true";
}
if ($enableInverseTextNormalization) {
    $request = $request . "&enable_inverse_text_normalization=" . "true";
}
if ($enableVoiceDetection) {
    $request = $request . "&enable_voice_detection=" . "true";
}

print "Request: " . $request . "\n";

process($token, $request, $audioFile);

?>

Node.js樣本

說明

在樣本檔案所在目錄執行如下命令安裝request依賴:npm install request --save

const request = require('request');
const fs = require('fs');


function callback(error, response, body) {
        if (error != null) {
                console.log(error);
        }
        else {
                console.log('The audio file recognized result:');
                console.log(body);
                if (response.statusCode == 200) {
                        body = JSON.parse(body);
                        if (body.status == 20000000) {
                                console.log('result: ' + body.result);
                                console.log('The audio file recognized succeed!');
                        } else {
                                console.log('The audio file recognized failed!');
                        }
                } else {
                        console.log('The audio file recognized failed, http code: ' + response.statusCode);
                }
        }
}

function process(requestUrl, token, audioFile) {
        /**
         * 讀取音頻檔案
        */
        var audioContent = null;
        try {
                audioContent = fs.readFileSync(audioFile);
        } catch(error) {
                if (error.code == 'ENOENT') {
                        console.log('The audio file is not exist!');
                }
                return;
        }

        /**
         * 設定HTTPS要求標頭部
        */
        var httpHeaders = {
                'X-NLS-Token': token,
                'Content-type': 'application/octet-stream',
                'Content-Length': audioContent.length
        };

        var options = {
                url: requestUrl,
                method: 'POST',
                headers: httpHeaders,
                body: audioContent
        };

        request(options, callback);
}


var appkey = '填入appkey';
var token = '填入服務鑒權Token';

var url = 'https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr';
var audioFile = '/path/to/nls-sample-16k.wav';
var format = 'pcm';
var sampleRate = '16000';
var enablePunctuationPrediction = true;
var enableInverseTextNormalization = true;
var enableVoiceDetection  = false;

/**
 * 設定RESTful請求參數
 */
var requestUrl = url;
requestUrl = requestUrl + '?appkey=' + appkey;
requestUrl = requestUrl + '&format=' + format;
requestUrl = requestUrl + '&sample_rate=' + sampleRate;
if (enablePunctuationPrediction) {
        requestUrl = requestUrl + '&enable_punctuation_prediction=' + 'true';
}
if (enableInverseTextNormalization) {
        requestUrl = requestUrl + '&enable_inverse_text_normalization=' + 'true';
}
if (enableVoiceDetection) {
        requestUrl = requestUrl + '&enable_voice_detection=' + 'true';
}

process(requestUrl, token, audioFile);

.Net樣本

說明

樣本依賴System.Net.Http和Newtonsoft.Json.Linq。

using System;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json.Linq;

namespace RESTfulAPI
{
    class SpeechRecognizerRESTfulDemo
    {
        private string token;
        private string appkey;

        public SpeechRecognizerRESTfulDemo(string appkey, string token)
        {
            this.appkey = appkey;
            this.token = token;
        }

        public void process(string fileName, string format, int sampleRate,
            bool enablePunctuationPrediction,
            bool enableInverseTextNormalization,
            bool enableVoiceDetection)
        {
            /**
             * 設定HTTPS REST POST請求
             * 1.使用HTTPS協議
             * 2.語音辨識服務網域名稱:nls-gateway-cn-shanghai.aliyuncs.com
             * 3.語音辨識介面請求路徑:/stream/v1/asr
             * 4.設定必選請求參數:appkey、format、sample_rate,
             * 5.設定可選請求參數:enable_punctuation_prediction、enable_inverse_text_normalization、enable_voice_detection
             */
            string url = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr";
            url = url + "?appkey=" + appkey;
            url = url + "&format=" + format;
            url = url + "&sample_rate=" + sampleRate;
            if (enablePunctuationPrediction)
            {
                url = url + "&enable_punctuation_prediction=" + true;
            }
            if (enableInverseTextNormalization)
            {
                url = url + "&enable_inverse_text_normalization=" + true;
            }
            if (enableVoiceDetection)
            {
                url = url + "&enable_voice_detection=" + true;
            }

            System.Console.WriteLine("URL: " + url);


            HttpClient client = new HttpClient();
            /**
             * 設定HTTPS頭部欄位
             * 鑒權參數
             */
            client.DefaultRequestHeaders.Add("X-NLS-Token", token);
            if (!File.Exists(fileName))
            {
                System.Console.WriteLine("The audio file dose not exist");
                return;
            }
            byte[] audioData = File.ReadAllBytes(fileName);

            /**
             * 設定HTTPS Body
             * 音頻位元據
             * Content-Type:application/octet-stream
             */
            ByteArrayContent content = new ByteArrayContent(audioData);
            content.Headers.Add("Content-Type", "application/octet-stream");

            /**
             * 發送HTTPS POST請求,處理服務端的響應。
             */
            HttpResponseMessage response = client.PostAsync(url, content).Result;

            string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
            System.Console.WriteLine("Response: " + responseBodyAsText);

            if (response.IsSuccessStatusCode)
            {
                JObject obj = JObject.Parse(responseBodyAsText);
                string result = obj["result"].ToString();
                System.Console.WriteLine("識別結果: " + result);
            }
            else
            {
                System.Console.WriteLine("Response status code and reason phrase: " +
                    response.StatusCode + " " + response.ReasonPhrase);
                System.Console.WriteLine("識別失敗!");
            }

        }

        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                System.Console.WriteLine("SpeechRecognizerRESTfulDemo need params: <token> <app-key>");
                return;
            }

            string token = args[0];
            string appkey = args[1];

            SpeechRecognizerRESTfulDemo demo = new SpeechRecognizerRESTfulDemo(appkey, token);

            string fileName = "nls-sample-16k.wav";
            string format = "pcm";
            int sampleRate = 16000;
            bool enablePunctuationPrediction = true;
            bool enableInverseTextNormalization = true;
            bool enableVoiceDetection = false;

            demo.process(fileName, format, sampleRate,
                enablePunctuationPrediction, enableInverseTextNormalization, enableVoiceDetection);

        }
    }
}

GO樣本

package main

import (
    "fmt"
        "encoding/json"
        "net/http"
        "io/ioutil"
        "strconv"
        "bytes"
)

func process(appkey string, token string, fileName string, format string, sampleRate int,
             enablePunctuationPrediction bool, enableInverseTextNormalization bool, enableVoiceDetection bool) {
                         
    /**
     * 設定HTTPS REST POST請求:
     * 1.使用HTTPS協議
     * 2.語音辨識服務網域名稱:nls-gateway-cn-shanghai.aliyuncs.com
     * 3.語音辨識介面請求路徑:/stream/v1/asr
     * 4.設定必選請求參數:appkey、format、sample_rate,
     * 5.設定可選請求參數:enable_punctuation_prediction、enable_inverse_text_normalization、enable_voice_detection
     */                 
        var url string = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/asr"
        url = url + "?appkey=" + appkey
        url = url + "&format=" + format
        url = url + "&sample_rate=" + strconv.Itoa(sampleRate)
        if (enablePunctuationPrediction) {
            url = url + "&enable_punctuation_prediction=" + "true"
        }
        if (enableInverseTextNormalization) {
            url = url + "&enable_inverse_text_normalization=" + "true"
        }
        if (enableVoiceDetection) {
            url = url + "&enable_voice_detection=" + "false"
        }

    fmt.Println(url)
        
        /**
         * 讀取音頻資料,作為HTTPS請求體。
         。*/
        audioData, err := ioutil.ReadFile(fileName)
        if err != nil {
            panic(err)
        }
        
        request, err := http.NewRequest("POST", url, bytes.NewBuffer(audioData))
        if err != nil {
            panic(err)
        }
        
        /**
     * 設定HTTPS頭部欄位:
     * 1.鑒權參數。
     * 2.Content-Type:application/octet-stream。
     */
        request.Header.Add("X-NLS-Token", token)
        request.Header.Add("Content-Type", "application/octet-stream")
        
        /**
     * 發送HTTPS POST請求,處理服務端的響應。
     */
        client := &http.Client{}
        response, err := client.Do(request)
        if err != nil {
            panic(err)
        }
        
        defer response.Body.Close()
        
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
        
        statusCode := response.StatusCode
        if (statusCode == 200) {
            var resultMap map[string]interface{}
            err = json.Unmarshal([]byte(body), &resultMap)
            if err != nil {
                panic(err)
            }
        
            var result string = resultMap["result"].(string)
            fmt.Println("識別成功:" + result)
        } else {
            fmt.Println("識別失敗,HTTP StatusCode: " + strconv.Itoa(statusCode))
        }
        
}

func main() {

    var appkey string = "填入appkey"
        var token  string = "填入token"
        
        var fileName string = "nls-sample-16k.wav"
        var format string = "pcm"
        var sampleRate int = 16000
        var enablePunctuationPrediction bool = true
        var enableInverseTextNormalization bool = true
        var enableVoiceDetection = false
        
        process(appkey, token, fileName, format, sampleRate, enablePunctuationPrediction, enableInverseTextNormalization, enableVoiceDetection)
        

}
  • 本頁導讀 (1, M)
  • 功能介紹
  • 前提條件
  • 互動流程
  • 服務地址
  • 輸入音頻
  • 上傳二進位音頻流
  • 使用音頻檔案連結
  • 響應結果
  • 服務狀態代碼
  • 快速測試
  • Java樣本
  • C++樣本
  • Python樣本
  • PHP樣本
  • Node.js樣本
  • .Net樣本
  • GO樣本
文檔反饋