全部產品
Search
文件中心

Intelligent Speech Interaction:RESTful API

更新時間:Sep 01, 2026

一句話識別 RESTful API 支援通過 HTTP POST 請求上傳不超過 1 分鐘的音頻。服務端處理完成後,在 HTTP 響應中一次性返回 JSON 格式的識別結果。

前提條件

調用介面前,需準備以下資訊:

音頻要求

要求

說明

編碼

單聲道、16 bit 採樣位元。

格式

PCM、PCM 編碼的 WAV、OGG 封裝的 Opus、OGG 封裝的 Speex、AMR。

採樣率

8000 Hz 或 16000 Hz。

時間長度

不超過 1 分鐘。

語種和情境模型不能通過請求參數指定。需在控制台為專案選擇與音頻匹配的模型,具體操作請參見管理專案。

重要

不要在瀏覽器前端代碼中直接調用該介面。瀏覽器可能因跨域資源共用(CORS)限制而拒絕請求,而且前端代碼會暴露 AppKey 和 Token。

快速測試

下載樣本音頻 nls-sample-16k.wav。該檔案為 16 kHz WAV 檔案,適用於通用模型。

設定 AppKey 和 Token 後,運行以下命令:

curl -X POST \
  -H "X-NLS-Token: <token>" \
  "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/asr?appkey=<appkey>&format=wav&sample_rate=16000" \
  --data-binary @nls-sample-16k.wav

成功響應樣本:

{
  "task_id": "cf7b0c5339244ee29cd4e43fb97f****",
  "result": "北京的天氣。",
  "status": 20000000,
  "message": "SUCCESS"
}

互動流程

用戶端在一個 HTTP POST 請求中發送鑒權資訊、請求參數和完整音頻。服務端處理完音頻後,在同一 HTTP 串連中返回一次 JSON 響應。收到響應前不要中斷串連。

  1. 用戶端向服務端發起 POST 請求。

  2. 服務端校正鑒權資訊和請求參數,並處理音頻。

  3. 服務端返回任務 ID、狀態代碼和識別結果。

服務地址

根據專案所在地區和網路環境選擇服務地址。公網地址支援 HTTPS 和 HTTP,建議使用 HTTPS。

地區

網路

服務地址

新加坡

公網

https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/asr

API 說明

請求由請求行、要求標頭和請求體組成。

請求行

POST /stream/v1/asr?appkey=<appkey>&format=pcm&sample_rate=16000&enable_punctuation_prediction=true HTTP/1.1

參數

類型

是否必選

預設值

說明

appkey

String

是

無

專案 AppKey。

format

String

否

pcm

音頻格式。取值:pcm、wav、opus、speex、amr。

sample_rate

Integer

否

16000

音頻採樣率。取值:8000、16000,單位為 Hz。

vocabulary_id

String

否

無

熱詞表 ID。

customization_id

String

否

無

自學習模型 ID。

enable_punctuation_prediction

Boolean

否

false

是否在後處理中添加標點。

enable_inverse_text_normalization

Boolean

否

false

是否啟用逆文本標準化,將口語數字轉換為阿拉伯數字等標準格式。

enable_voice_detection

Boolean

否

false

是否啟用語音活動檢測(VAD),自動檢測有效語音的開始和結束。

disfluency

Boolean

否

false

是否過濾語氣詞。

要求標頭

要求標頭

類型

是否必選

說明

X-NLS-Token

String

是

用於身分識別驗證的訪問 Token。

Content-Type

String

是

application/octet-stream

Content-Length

Long

是

請求體中的音頻資料大小,單位為位元組。

Host

String

是

nls-gateway-ap-southeast-1.aliyuncs.com。

請求體

將完整音訊位元據寫入請求體,並將 Content-Type 設定為 application/octet-stream。

請求樣本

POST /stream/v1/asr?appkey=23f5****&format=pcm&sample_rate=16000 HTTP/1.1
X-NLS-Token: 450372e4279bcc2b3c793****
Content-Type: application/octet-stream
Content-Length: 94616
Host: nls-gateway-ap-southeast-1.aliyuncs.com

[audio data]

響應說明

響應參數

參數

類型

說明

task_id

String

32 位任務 ID。排查問題時需提供該 ID。

result

String

識別結果。識別失敗時為空白字串。

status

Integer

狀態代碼。

message

String

狀態說明。

成功響應

{
  "task_id": "cf7b0c5339244ee29cd4e43fb97f****",
  "result": "北京的天氣。",
  "status": 20000000,
  "message": "SUCCESS"
}

失敗響應

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

排查失敗請求時,記錄響應中的任務 ID。

狀態代碼

出現偶發的服務端錯誤(5xxxxxxx)時可以重試。如果錯誤持續出現,請提交工單並提供響應中的任務 ID。

狀態代碼

說明

處理建議

20000000

請求成功。

無需處理。

40000000

用戶端錯誤。

根據錯誤訊息檢查請求。

40000001

身分識別驗證失敗。

檢查 Token 是否正確且未到期。

40000002

請求無效。

檢查請求是否符合介面要求。

40000003

參數無效。

檢查參數值是否在有效範圍內。

40000004

用戶端逾時。

檢查用戶端是否停止發送資料。

40000005

請求速率超限。

檢查並發數或 QPS 是否超過限制。

41010100

音頻格式不支援。

檢查 format 參數和實際音頻格式。

41010101

採樣率不支援。

檢查 sample_rate 是否與音頻和專案模型匹配。

50000000

服務端錯誤。

持續出現時提交工單並提供任務 ID。

50000001

服務內部調用錯誤。

持續出現時提交工單並提供任務 ID。

範例程式碼

以下樣本從環境變數讀取服務地址、AppKey、Token 和本地音頻路徑,並以二進位方式發送 PCM 音頻。

擷取 Token 的方法,請參見Obtain an access token。

環境變數

說明

NLS_ENDPOINT

https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/asr

NLS_APP_KEY

專案 AppKey。

NLS_TOKEN

有效訪問 Token。

NLS_AUDIO_FILE

16 kHz、16 bit、單聲道 PCM 音頻檔案的本地路徑。

Java

樣本使用 JDK 21。

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

public class SpeechRecognition {
    private static String required(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) {
            throw new IllegalArgumentException("Missing environment variable: " + name);
        }
        return value;
    }

    public static void main(String[] args) throws Exception {
        String endpoint = required("NLS_ENDPOINT");
        String appKey = URLEncoder.encode(required("NLS_APP_KEY"), StandardCharsets.UTF_8);
        String token = required("NLS_TOKEN");
        Path audioFile = Path.of(required("NLS_AUDIO_FILE"));
        String url = endpoint + "?appkey=" + appKey
                + "&format=pcm&sample_rate=16000"
                + "&enable_punctuation_prediction=true"
                + "&enable_inverse_text_normalization=true";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
                .header("X-NLS-Token", token)
                .header("Content-Type", "application/octet-stream")
                .POST(HttpRequest.BodyPublishers.ofFile(audioFile))
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(
                request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        System.out.println(response.body());
    }
}

C++

樣本使用 C++17 and libcurl 8.7.1。

#include <curl/curl.h>

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>

std::string required(const char* name) {
    const char* value = std::getenv(name);
    if (value == nullptr || *value == '\0') {
        throw std::runtime_error(std::string("Missing environment variable: ") + name);
    }
    return value;
}

size_t writeResponse(char* data, size_t size, size_t count, void* target) {
    static_cast<std::string*>(target)->append(data, size * count);
    return size * count;
}

int main() {
    std::ifstream file(required("NLS_AUDIO_FILE"), std::ios::binary);
    if (!file) throw std::runtime_error("Cannot open audio file");
    std::string audio((std::istreambuf_iterator<char>(file)),
                      std::istreambuf_iterator<char>());

    curl_global_init(CURL_GLOBAL_DEFAULT);
    CURL* curl = curl_easy_init();
    if (curl == nullptr) throw std::runtime_error("Cannot initialize cURL");
    char* escaped = curl_easy_escape(curl, required("NLS_APP_KEY").c_str(), 0);
    std::string url = required("NLS_ENDPOINT") + "?appkey=" + escaped
            + "&format=pcm&sample_rate=16000"
            + "&enable_punctuation_prediction=true"
            + "&enable_inverse_text_normalization=true";
    curl_free(escaped);

    std::string response;
    std::string tokenHeader = "X-NLS-Token: " + required("NLS_TOKEN");
    curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, tokenHeader.c_str());
    headers = curl_slist_append(headers, "Content-Type: application/octet-stream");
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, audio.data());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(audio.size()));
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeResponse);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    CURLcode code = curl_easy_perform(curl);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
    std::cout << response << std::endl;
}

Python

樣本使用 Python 3.14。

import os
import urllib.parse
import urllib.request


def required(name):
    value = os.getenv(name)
    if not value:
        raise RuntimeError(f"Missing environment variable: {name}")
    return value


endpoint = required("NLS_ENDPOINT")
query = urllib.parse.urlencode({
    "appkey": required("NLS_APP_KEY"),
    "format": "pcm",
    "sample_rate": 16000,
    "enable_punctuation_prediction": "true",
    "enable_inverse_text_normalization": "true",
})
with open(required("NLS_AUDIO_FILE"), "rb") as audio_file:
    request = urllib.request.Request(
        f"{endpoint}?{query}",
        data=audio_file.read(),
        headers={
            "X-NLS-Token": required("NLS_TOKEN"),
            "Content-Type": "application/octet-stream",
        },
        method="POST",
    )
with urllib.request.urlopen(request) as response:
    print(response.read().decode("utf-8"))

PHP

樣本使用 PHP 8.5 with the cURL extension。

<?php

function required_env(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Missing environment variable: " . $name);
    }
    return $value;
}

$query = http_build_query([
    'appkey' => required_env('NLS_APP_KEY'),
    'format' => 'pcm',
    'sample_rate' => 16000,
    'enable_punctuation_prediction' => 'true',
    'enable_inverse_text_normalization' => 'true',
]);
$audio = file_get_contents(required_env('NLS_AUDIO_FILE'));
if ($audio === false) {
    throw new RuntimeException('Cannot read the audio file');
}

$curl = curl_init(required_env('NLS_ENDPOINT') . '?' . $query);
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $audio,
    CURLOPT_HTTPHEADER => [
        'X-NLS-Token: ' . required_env('NLS_TOKEN'),
        'Content-Type: application/octet-stream',
    ],
    CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($curl);
if ($response === false) {
    throw new RuntimeException(curl_error($curl));
}
echo $response . PHP_EOL;

Node.js

樣本使用 Node.js 22。

import fs from "node:fs";
import http from "node:http";
import https from "node:https";

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable: ${name}`);
  return value;
}

const endpoint = new URL(required("NLS_ENDPOINT"));
endpoint.search = new URLSearchParams({
  appkey: required("NLS_APP_KEY"),
  format: "pcm",
  sample_rate: "16000",
  enable_punctuation_prediction: "true",
  enable_inverse_text_normalization: "true",
});
const audio = fs.readFileSync(required("NLS_AUDIO_FILE"));
const transport = endpoint.protocol === "https:" ? https : http;

const request = transport.request(endpoint, {
  method: "POST",
  headers: {
    "X-NLS-Token": required("NLS_TOKEN"),
    "Content-Type": "application/octet-stream",
    "Content-Length": audio.length,
  },
}, (response) => {
  let body = "";
  response.setEncoding("utf8");
  response.on("data", (chunk) => { body += chunk; });
  response.on("end", () => console.log(body));
});
request.on("error", (error) => { throw error; });
request.end(audio);

C#

樣本使用 .NET 8。

using System.Net.Http.Headers;

static string Required(string name)
{
    string? value = Environment.GetEnvironmentVariable(name);
    if (string.IsNullOrWhiteSpace(value))
        throw new ArgumentException($"Missing environment variable: {name}");
    return value;
}

string query = string.Join("&", new Dictionary<string, string>
{
    ["appkey"] = Required("NLS_APP_KEY"),
    ["format"] = "pcm",
    ["sample_rate"] = "16000",
    ["enable_punctuation_prediction"] = "true",
    ["enable_inverse_text_normalization"] = "true",
}.Select(item => $"{Uri.EscapeDataString(item.Key)}={Uri.EscapeDataString(item.Value)}"));

using HttpClient client = new();
using ByteArrayContent audio = new(await File.ReadAllBytesAsync(Required("NLS_AUDIO_FILE")));
audio.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
using HttpRequestMessage request = new(HttpMethod.Post, $"{Required("NLS_ENDPOINT")}?{query}");
request.Headers.Add("X-NLS-Token", Required("NLS_TOKEN"));
request.Content = audio;
using HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());

Go

樣本使用 Go 1.24。

package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
)

func required(name string) string {
	value := os.Getenv(name)
	if value == "" {
		panic("Missing environment variable: " + name)
	}
	return value
}

func main() {
	audio, err := os.ReadFile(required("NLS_AUDIO_FILE"))
	if err != nil {
		panic(err)
	}
	query := url.Values{
		"appkey":                            {required("NLS_APP_KEY")},
		"format":                            {"pcm"},
		"sample_rate":                       {"16000"},
		"enable_punctuation_prediction":     {"true"},
		"enable_inverse_text_normalization": {"true"},
	}
	request, err := http.NewRequest(
		http.MethodPost, required("NLS_ENDPOINT")+"?"+query.Encode(), bytes.NewReader(audio))
	if err != nil {
		panic(err)
	}
	request.Header.Set("X-NLS-Token", required("NLS_TOKEN"))
	request.Header.Set("Content-Type", "application/octet-stream")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}

相關文檔