全部產品
Search
文件中心

Intelligent Speech Interaction:RESTful API

更新時間:Oct 28, 2026

語音合成 RESTful API 通過 HTTPS GET 或 POST 請求接收文本,並在響應體中返回合成音頻。支援設定音頻格式、採樣率、發音人、語速、語調和音量。

功能說明

支援 PCM、WAV 和 MP3 音頻格式,以及多種發音人。音頻格式和採樣率等配置見請求參數。

重要
  • 單次請求的文本不超過 300 個字元,超過的字元會被截斷。更長的文本需要分段合成,再拼接音頻。

  • 合成耗時受文本和模型影響。建議採用流式接收,收到音頻資料後即可處理,不必等待全部音頻返回。在響應讀取完成前,保持串連不中斷。

前提條件

服務地址

使用與服務地區對應的 AppKey 和 Token。以下樣本使用公網 HTTPS 地址。

地區

請求 URL

新加坡

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

範例程式碼

將樣本中的 AppKey 和 Token 佔位值替換為有效憑證。不要在日誌中記錄 Token、攜帶 Token 的完整 URL 或請求體。各語言樣本示範 GET 和 POST 請求;Java 還提供流式接收樣本。

Java

依賴

將以下依賴加入 Maven 專案的 pom.xml:

<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>
<dependency>
    <groupId>org.asynchttpclient</groupId>
    <artifactId>async-http-client</artifactId>
    <version>2.5.4</version>
</dependency>

普通請求

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SpeechSynthesizerRestfulDemo {
    private String accessToken;
    private String appkey;
    public SpeechSynthesizerRestfulDemo(String appkey, String token) {
        this.appkey = appkey;
        this.accessToken = token;
    }
    /**
     * HTTPS GET請求
     */
    public void processGETRequet(String text, String audioSaveFile, String format, int sampleRate, String voice) {
        /**
         * 設定HTTPS GET請求:
         * 1.使用HTTPS協議
         * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
         * 3.語音合成介面請求路徑:/stream/v1/tts
         * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
         * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
         */
        String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
        url = url + "?appkey=" + appkey;
        url = url + "&token=" + accessToken;
        url = url + "&text=" + text;
        url = url + "&format=" + format;
        url = url + "&voice=" + voice;
        url = url + "&sample_rate=" + String.valueOf(sampleRate);
        // voice 發音人,可選,預設是xiaoyun。
        // url = url + "&voice=" + "xiaoyun";
        // volume 音量,範圍是0~100,可選,預設50。
        // url = url + "&volume=" + String.valueOf(50);
        // speech_rate 語速,範圍是-500~500,可選,預設是0。
        // url = url + "&speech_rate=" + String.valueOf(0);
        // pitch_rate 語調,範圍是-500~500,可選,預設是0。
        // url = url + "&pitch_rate=" + String.valueOf(0);
        /**
         * 發送HTTPS GET請求,處理服務端的響應。
         */
        Request request = new Request.Builder().url(url).get().build();
        try {
            long start = System.currentTimeMillis();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            System.out.println("total latency :" + (System.currentTimeMillis() - start) + " ms");
            System.out.println(response.headers().toString());
            String contentType = response.header("Content-Type");
            if ("audio/mpeg".equals(contentType)) {
                File f = new File(audioSaveFile);
                FileOutputStream fout = new FileOutputStream(f);
                fout.write(response.body().bytes());
                fout.close();
                System.out.println("The GET request succeed!");
            }
            else {
                // ContentType 為 null 或者為 "application/json"
                String errorMessage = response.body().string();
                System.out.println("The GET request failed: " + errorMessage);
            }
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * HTTPS POST請求
     */
    public void processPOSTRequest(String text, String audioSaveFile, String format, int sampleRate, String voice) {
        /**
         * 設定HTTPS POST請求:
         * 1.使用HTTPS協議
         * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
         * 3.語音合成介面請求路徑:/stream/v1/tts
         * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
         * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
         */
        String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
        JSONObject taskObject = new JSONObject();
        taskObject.put("appkey", appkey);
        taskObject.put("token", accessToken);
        taskObject.put("text", text);
        taskObject.put("format", format);
        taskObject.put("voice", voice);
        taskObject.put("sample_rate", sampleRate);
        // voice 發音人,可選,預設是xiaoyun。
        // taskObject.put("voice", "xiaoyun");
        // volume 音量,範圍是0~100,可選,預設50。
        // taskObject.put("volume", 50);
        // speech_rate 語速,範圍是-500~500,可選,預設是0。
        // taskObject.put("speech_rate", 0);
        // pitch_rate 語調,範圍是-500~500,可選,預設是0。
        // taskObject.put("pitch_rate", 0);
        String bodyContent = taskObject.toJSONString();
        RequestBody reqBody = RequestBody.create(MediaType.parse("application/json"), bodyContent);
        Request request = new Request.Builder()
            .url(url)
            .header("Content-Type", "application/json")
            .post(reqBody)
            .build();
        try {
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            String contentType = response.header("Content-Type");
            if ("audio/mpeg".equals(contentType)) {
                File f = new File(audioSaveFile);
                FileOutputStream fout = new FileOutputStream(f);
                fout.write(response.body().bytes());
                fout.close();
                System.out.println("The POST request succeed!");
            }
            else {
                // ContentType 為 null 或者為 "application/json"
                String errorMessage = response.body().string();
                System.out.println("The POST request failed: " + errorMessage);
            }
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("SpeechSynthesizerRestfulDemo need params: <token> <app-key>");
            System.exit(-1);
        }
        String token = args[0];
        String appkey = args[1];
        SpeechSynthesizerRestfulDemo demo = new SpeechSynthesizerRestfulDemo(appkey, token);
        String text = "今天是周一,天氣挺好的。";
        // 採用RFC 3986規範進行urlencode編碼。
        String textUrlEncode = text;
        try {
            textUrlEncode = URLEncoder.encode(textUrlEncode, "UTF-8")
                .replace("+", "%20")
                .replace("*", "%2A")
                .replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(textUrlEncode);
        String audioSaveFile = "syAudio.wav";
        String format = "wav";
        int sampleRate = 16000;
        demo.processGETRequet(textUrlEncode, audioSaveFile, format, sampleRate, "siyue");
        //demo.processPOSTRequest(text, audioSaveFile, format, sampleRate, "siyue");
        System.out.println("### Game Over ###");
    }
}

流式接收

通過響應回調分段接收音頻。不要在回調中執行耗時操作;需要播放或進一步處理時,可將音頻資料交給其他線程。

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.CountDownLatch;
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 此樣本示範了
 * 1. TTS的RESTFul介面調用。
 * 2. 啟用HTTP chunked機制的處理方式(流式返回)。
 */
public class SpeechSynthesizerRestfulChunkedDemo {
    private static Logger logger = LoggerFactory.getLogger(SpeechSynthesizerRestfulChunkedDemo.class);
    private String accessToken;
    private String appkey;
    public SpeechSynthesizerRestfulChunkedDemo(String appkey, String token) {
        this.appkey = appkey;
        this.accessToken = token;
    }
    public void processGETRequet(String text, String audioSaveFile, String format, int sampleRate, String voice, boolean chunked) {
        /**
         * 設定HTTPS GET請求:
         * 1.使用HTTPS協議
         * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
         * 3.語音合成介面請求路徑:/stream/v1/tts
         * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
         * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
         * 6.設定參數chunk,啟用http流式返回
         */
        String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
        url = url + "?appkey=" + appkey;
        url = url + "&token=" + accessToken;
        url = url + "&text=" + text;
        url = url + "&format=" + format;
        url = url + "&voice=" + voice;
        url = url + "&sample_rate=" + String.valueOf(sampleRate);
        url = url + "&chunk=" + String.valueOf(chunked);
        try {
            AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
                .setConnectTimeout(3000)
                .setKeepAlive(true)
                .setReadTimeout(10000)
                .setRequestTimeout(50000)
                .setMaxConnections(1000)
                .setMaxConnectionsPerHost(200)
                .setPooledConnectionIdleTimeout(-1)
                .build();
            AsyncHttpClient httpClient = new DefaultAsyncHttpClient(config);
            CountDownLatch latch = new CountDownLatch(1);
            AsyncHandler<org.asynchttpclient.Response> handler = new AsyncHandler<org.asynchttpclient.Response>() {
                FileOutputStream outs;
                boolean firstRecvBinary = true;
                long startTime = System.currentTimeMillis();
                int httpCode = 200;
                @Override
                public State onStatusReceived(HttpResponseStatus httpResponseStatus) throws Exception {
                    logger.info("onStatusReceived status {}", httpResponseStatus);
                    httpCode = httpResponseStatus.getStatusCode();
                    if (httpResponseStatus.getStatusCode() != 200) {
                        logger.error("request error " +  httpResponseStatus.toString());
                    }
                    return State.CONTINUE;
                }
                @Override
                public State onHeadersReceived(HttpHeaders httpHeaders) throws Exception {
                    if (httpCode != 200 || !"audio/mpeg".equals(httpHeaders.get("Content-Type"))) {
                        throw new java.io.IOException("Unexpected synthesis response: HTTP " + httpCode);
                    }
                    outs = new FileOutputStream(new File(audioSaveFile));
                    return State.CONTINUE;
                }
                @Override
                public State onBodyPartReceived(HttpResponseBodyPart httpResponseBodyPart) throws Exception {
                    // 注意:此處一旦接收到資料流,即可向使用者播放或者用於其他處理,以提升響應速度。
                    // 注意:請不要在此回調介面中執行耗時操作,可以以非同步或者隊列形式將二進位TTS語音流推送到另一線程中。
                    logger.info("onBodyPartReceived " + httpResponseBodyPart.getBodyPartBytes().toString());
                    if(httpCode != 200) {
                        System.err.write(httpResponseBodyPart.getBodyPartBytes());
                    }
                    if (firstRecvBinary) {
                        firstRecvBinary = false;
                        // 統計第一包資料的接收延遲。實際上接收到第一包資料後就可以進行業務處理了,比如播放或者發送給調用方。注意:這裡的首包延遲也包括了網路建立連結的時間。
                        logger.info("tts first latency " + (System.currentTimeMillis() - startTime) + " ms");
                    }
                    // 此處以將語音流儲存到檔案為例。
                    outs.write(httpResponseBodyPart.getBodyPartBytes());
                    return State.CONTINUE;
                }
                @Override
                public void onThrowable(Throwable throwable) {
                    logger.error("Synthesis request failed: {}", throwable.getClass().getSimpleName());
                    if (outs != null) {
                        try { outs.close(); } catch (java.io.IOException ignored) { }
                    }
                    latch.countDown();
                }
                @Override
                public org.asynchttpclient.Response onCompleted() throws Exception {
                    logger.info("completed");
                    logger.info("tts total latency " + (System.currentTimeMillis() - startTime) + " ms");
                    outs.close();
                    latch.countDown();
                    return null;
                }
            };
            httpClient.prepareGet(url).execute(handler);
            // 等待合成完成
            latch.await();
            httpClient.close();
        }catch (Exception e) {
        }
    }
    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("SpeechSynthesizerRestfulDemo need params: <token> <app-key>");
            System.exit(-1);
        }
        String token = args[0];
        String appkey = args[1];
        SpeechSynthesizerRestfulChunkedDemo demo = new SpeechSynthesizerRestfulChunkedDemo(appkey, token);
        String text = "今天是周一,天氣挺好的。";
        // 採用RFC 3986規範進行urlencode編碼。
        String textUrlEncode = text;
        try {
            textUrlEncode = URLEncoder.encode(textUrlEncode, "UTF-8")
                .replace("+", "%20")
                .replace("*", "%2A")
                .replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(textUrlEncode);
        String audioSaveFile = "syAudio.wav";
        String format = "wav";
        int sampleRate = 16000;
        // 最後一個參數為true表示使用http chunked機制。
        demo.processGETRequet(textUrlEncode, audioSaveFile, format, sampleRate, "aixia", true);
        System.out.println("### Game Over ###");
    }
}

分段合成長文本的完整樣本可下載 nls-restful-java-demo.zip。

C++

說明
  • 下載C++樣本。

    C++樣本使用第三方函數庫curl處理HTTPS的請求和響應,使用jsoncpp處理POST請求體的JSON字串。

  • Linux環境下,運行環境最低要求:Glibc 2.5及以上, GCC 4或GCC 5。

  • Windows下需解壓lib目錄下的windows.zip庫編譯使用。

樣本目錄說明如下:

  • CMakeLists.txt:樣本工程的CMakeList檔案。

  • demo:樣本檔案。

    檔案名稱

    描述

    restfulTtsDemo.cpp

    語音合成RESTful API樣本。

  • include

    目錄名

    描述

    curl

    curl庫標頭檔目錄。

    json

    jsoncpp庫標頭檔目錄。

  • lib:包含curl、jsoncpp動態庫。

    根據平台不同,使用如下版本軟體載入庫檔案:

    • 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. ./restfulTtsDemo <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 restfulTtsDemo restfulTtsDemo.cpp -I path/to/sdk/include -L path/to/sdk/lib/linux -ljsoncpp -lssl -lcrypto -lcurl -D_GLIBCXX_USE_CXX11_ABI=0。

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

    6. ./restfulTtsDemo <your-token> <your-appkey>。

範例程式碼如下:

#ifdef _WIN32
#include <Windows.h>
#endif
#include <iostream>
#include <string>
#include <map>
#include <fstream>
#include <sstream>
#include "curl/curl.h"
#include "json/json.h"
using namespace std;
#ifdef _WIN32
string GBKToUTF8(const string &strGBK) {
    string strOutUTF8 = "";
    WCHAR * str1;
    int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
    str1 = new WCHAR[n];
    MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
    n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
    char * str2 = new char[n];
    WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
    strOutUTF8 = str2;
    delete[] str1;
    str1 = NULL;
    delete[] str2;
    str2 = NULL;
    return strOutUTF8;
}
#endif
void stringReplace(string& src, const string& s1, const string& s2) {
    string::size_type pos = 0;
    while ((pos = src.find(s1, pos)) != string::npos) {
        src.replace(pos, s1.length(), s2);
        pos += s2.length();
    }
}
string urlEncode(const string& src) {
    CURL* curl = curl_easy_init();
    char* output = curl_easy_escape(curl, src.c_str(), src.size());
    string result(output);
    curl_free(output);
    curl_easy_cleanup(curl);
    return result;
}
size_t responseHeadersCallback(void* ptr, size_t size, size_t nmemb, void* userdata)
{
    map<string, string> *headers = (map<string, string>*)userdata;
    string line((char*)ptr, size * nmemb);
    string::size_type pos = line.find(':');
    if (pos != line.npos)
    {
        string name = line.substr(0, pos);
        string value = line.substr(pos + 2);
        size_t p = 0;
        if ((p = value.rfind('\r')) != value.npos) {
            value = value.substr(0, p);
        }
        headers->insert(make_pair(name, value));
    }
    return size * nmemb;
}
size_t responseBodyCallback(void* ptr, size_t size, size_t nmemb, void* userData) {
    size_t len = size * nmemb;
    char* pBuf = (char*)ptr;
    string* bodyContent = (string*)userData;
    (*bodyContent).append(string(pBuf, pBuf + len));
    return len;
}
int processGETRequest(string appKey, string token, string text, 
                      string audioSaveFile, string format, int sampleRate) {
    CURL* curl = NULL;
    CURLcode res;
    curl = curl_easy_init();
    if (curl == NULL) {
        return -1;
    }
    string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
    /**
     * 設定HTTPS URL請求參數
     */
    ostringstream oss;
    oss << url;
    oss << "?appkey=" << appKey;
    oss << "&token=" << token;
    oss << "&text=" << text;
    oss << "&format=" << format;
    oss << "&sample_rate=" << sampleRate;
    // voice 發音人,可選,預設是xiaoyun。
    // oss << "&voice=" << "xiaoyun";
    // volume 音量,範圍是0~100,可選,預設50。
    // oss << "&volume=" << 50;
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // oss << "&speech_rate=" << 0;
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // oss << "&pitch_rate=" << 0;
    string request = oss.str();
    curl_easy_setopt(curl, CURLOPT_URL, request.c_str());
    /**
     * 設定擷取響應的HTTPS Headers回呼函數
     */
    map<string, string> responseHeaders;
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, responseHeadersCallback);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders);
    /**
     * 設定擷取響應的HTTPS Body回呼函數
     */
    string bodyContent = "";
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseBodyCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyContent);
    /**
     * 發送HTTPS GET請求
     */
    res = curl_easy_perform(curl);
    /**
     * 釋放資源
     */
    curl_easy_cleanup(curl);
    if (res != CURLE_OK) {
        cerr << "curl_easy_perform failed: " << curl_easy_strerror(res) << endl;
        return -1;
    }
    /**
     * 處理服務端返回的響應
     */
    map<string, string>::iterator it = responseHeaders.find("Content-Type");
    if (it != responseHeaders.end() && it->second.compare("audio/mpeg") == 0) {
        ofstream fs;
        fs.open(audioSaveFile.c_str(), ios::out | ios::binary);
        if (!fs.is_open()) {
            cout << "The audio save file can not open!";
            return -1;
        }
        fs.write(bodyContent.c_str(), bodyContent.size());
        fs.close();
        cout << "The GET request succeed!" << endl;
    }
    else {
        cout << "The GET request failed: " + bodyContent << endl;
        return -1;
    }
    return 0;
}
int processPOSTRequest(string appKey, string token, string text,
                       string audioSaveFile, string format, int sampleRate) {
    CURL* curl = NULL;
    CURLcode res;
    curl = curl_easy_init();
    if (curl == NULL) {
        return -1;
    }
    string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
    /**
     * 設定HTTPS POST URL
     */
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    /**
     * 設定HTTPS POST要求標頭部
     */
    struct curl_slist* headers = NULL;
    // Content-Type
    headers = curl_slist_append(headers, "Content-Type:application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    /**
     * 設定HTTPS POST請求體
     */
    Json::Value root;
    Json::FastWriter writer;
    root["appkey"] = appKey;
    root["token"] = token;
    root["text"] = text;
    root["format"] = format;
    root["sample_rate"] = sampleRate;
    // voice 發音人,可選,預設是xiaoyun。
    // root["voice"] = "xiaoyun";
    // volume 音量,範圍是0~100,可選,預設50。
    // root["volume"] = 50;
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // root["speech_rate"] = 0;
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // root["pitch_rate"] = 0;
    string task = writer.write(root);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, task.c_str());
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, task.length());
    /**
     * 設定擷取響應的HTTPS Headers回呼函數
     */
    map<string, string> responseHeaders;
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, responseHeadersCallback);
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders);
    /**
     * 設定擷取響應的HTTPS Body回呼函數
     */
    string bodyContent = "";
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseBodyCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyContent);
    /**
     * 發送HTTPS POST請求
     */
    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;
    }
    /**
     * 處理服務端返回的響應
     */
    map<string, string>::iterator it = responseHeaders.find("Content-Type");
    if (it != responseHeaders.end() && it->second.compare("audio/mpeg") == 0) {
        ofstream fs;
        fs.open(audioSaveFile.c_str(), ios::out | ios::binary);
        if (!fs.is_open()) {
            cout << "The audio save file can not open!";
            return -1;
        }
        fs.write(bodyContent.c_str(), bodyContent.size());
        fs.close();
        cout << "The POST request succeed!" << endl;
    }
    else {
        cout << "The POST request failed: " + bodyContent << endl;
        return -1;
    }
    return 0;
}
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 text = "今天是周一,天氣挺好的。";
#ifdef _WIN32
    text = GBKToUTF8(text);
#endif
    string textUrlEncode = urlEncode(text);
    stringReplace(textUrlEncode, "+", "%20");
    stringReplace(textUrlEncode, "*", "%2A");
    stringReplace(textUrlEncode, "%7E", "~");
    string audioSaveFile = "syAudio.wav";
    string format = "wav";
    int sampleRate = 16000;
    // 全域只初始化一次。
    curl_global_init(CURL_GLOBAL_ALL);
    processGETRequest(appKey, token, textUrlEncode, audioSaveFile, format, sampleRate);
    //processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate);
    curl_global_cleanup();
    return 0;
}

Python

Python 3 使用 http.client 和 urllib.parse。Python 2 對應使用 httplib 和 urllib,替換方式見代碼注釋。

# -*- coding: UTF-8 -*-
# Python 2.x引入httplib模組。
# import httplib
# Python 3.x引入http.client模組。
import http.client
# Python 2.x引入urllib模組。
# import urllib
# Python 3.x引入urllib.parse模組。
import urllib.parse
import json
def processGETRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
    host = 'nls-gateway-ap-southeast-1.aliyuncs.com'
    url = 'https://' + host + '/stream/v1/tts'
    # 設定URL請求參數
    url = url + '?appkey=' + appKey
    url = url + '&token=' + token
    url = url + '&text=' + text
    url = url + '&format=' + format
    url = url + '&sample_rate=' + str(sampleRate)
    # voice 發音人,可選,預設是xiaoyun。
    # url = url + '&voice=' + 'xiaoyun'
    # volume 音量,範圍是0~100,可選,預設50。
    # url = url + '&volume=' + str(50)
    # speech_rate 語速,範圍是-500~500,可選,預設是0。
    # url = url + '&speech_rate=' + str(0)
    # pitch_rate 語調,範圍是-500~500,可選,預設是0。
    # url = url + '&pitch_rate=' + str(0)
    # Python 2.x請使用httplib。
    # conn = httplib.HTTPSConnection(host)
    # Python 3.x請使用http.client。
    conn = http.client.HTTPSConnection(host)
    conn.request(method='GET', url=url)
    # 處理服務端返回的響應。
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if 'audio/mpeg' == contentType :
        with open(audioSaveFile, mode='wb') as f:
            f.write(body)
        print('The GET request succeed!')
    else :
        print('The GET request failed: ' + str(body))
    conn.close()
def processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
    host = 'nls-gateway-ap-southeast-1.aliyuncs.com'
    url = 'https://' + host + '/stream/v1/tts'
    # 設定HTTPS Headers。
    httpHeaders = {
        'Content-Type': 'application/json'
        }
    # 設定HTTPS Body。
    body = {'appkey': appKey, 'token': token, 'text': text, 'format': format, 'sample_rate': sampleRate}
    body = json.dumps(body)
    # Python 2.x請使用httplib。
    # conn = httplib.HTTPSConnection(host)
    # Python 3.x請使用http.client。
    conn = http.client.HTTPSConnection(host)
    conn.request(method='POST', url=url, body=body, headers=httpHeaders)
    # 處理服務端返回的響應。
    response = conn.getresponse()
    print('Response status and response reason:')
    print(response.status ,response.reason)
    contentType = response.getheader('Content-Type')
    print(contentType)
    body = response.read()
    if 'audio/mpeg' == contentType :
        with open(audioSaveFile, mode='wb') as f:
            f.write(body)
        print('The POST request succeed!')
    else :
        print('The POST request failed: ' + str(body))
    conn.close()
appKey = '<appkey>'
token = '<token>'
text = '今天是周一,天氣挺好的。'
# 採用RFC 3986規範進行urlencode編碼。
textUrlencode = text
# Python 2.x請使用urllib.quote。
# textUrlencode = urllib.quote(textUrlencode, '')
# Python 3.x請使用urllib.parse.quote_plus。
textUrlencode = urllib.parse.quote_plus(textUrlencode)
textUrlencode = textUrlencode.replace("+", "%20")
textUrlencode = textUrlencode.replace("*", "%2A")
textUrlencode = textUrlencode.replace("%7E", "~")
print('text: ' + textUrlencode)
audioSaveFile = 'syAudio.wav'
format = 'wav'
sampleRate = 16000
# GET請求方式
processGETRequest(appKey, token, textUrlencode, audioSaveFile, format, sampleRate)
# POST請求方式
# processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate)

PHP

需要支援 json_encode 的 PHP 環境,並安裝 cURL 擴充。使用 HTTPS 時保留認證校正。

<?php
function processGETRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate) {
    $url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
    $url = $url . "?appkey=" . $appkey;
    $url = $url . "&token=" . $token;
    $url = $url . "&text=" . $text;
    $url = $url . "&format=" . $format;
    $url = $url . "&sample_rate=" . strval($sampleRate);
    // voice 發音人,可選,預設是xiaoyun。
    // $url = $url . "&voice=" . "xiaoyun";
    // volume 音量,範圍是0~100,可選,預設50。
    // $url = $url . "&volume=" . strval(50);
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // $url = $url . "&speech_rate=" . strval(0);
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // $url = $url . "&pitch_rate=" . strval(0);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    /**
     * 設定HTTPS GET URL。
     */
    curl_setopt($curl, CURLOPT_URL, $url);
    /**
     * 設定返回的響應包含HTTPS頭部資訊。
     */
    curl_setopt($curl, CURLOPT_HEADER, TRUE);
    /**
     * 發送HTTPS GET請求。
     */
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    $response = curl_exec($curl);
    if ($response == FALSE) {
        print "curl_exec failed!\n";
        curl_close($curl);
        return ;
    }
    /**
     * 處理服務端返回的響應。
     */
    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    $bodyContent = substr($response, $headerSize);
    curl_close($curl);
    if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
        file_put_contents($audioSaveFile, $bodyContent);
        print "The GET request succeed!\n";
    }
    else {
        print "The GET request failed: " . $bodyContent . "\n";
    }
}
function processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate) {
    $url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
    /**
     * 請求參數,以JSON格式字串填入HTTPS POST請求的Body中。
     */
    $taskArr = array(
        "appkey" => $appkey,
        "token" => $token,
        "text" => $text,
        "format" => $format,
        "sample_rate" => $sampleRate
        // voice 發音人,可選,預設是xiaoyun。
        // "voice" => "xiaoyun",
        // volume 音量,範圍是0~100,可選,預設50。
        // "volume" => 50,
        // speech_rate 語速,範圍是-500~500,可選,預設是0。
        // "speech_rate" => 0,
        // pitch_rate 語調,範圍是-500~500,可選,預設是0。
        // "pitch_rate" => 0
    );
    $body = json_encode($taskArr);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    /**
     * 設定HTTPS POST URL。
     */
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, TRUE);
    /**
     * 設定HTTPS POST要求標頭部。
     * */
    $httpHeaders = array(
        "Content-Type: application/json"
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
    /**
     * 設定HTTPS POST請求體。
     */
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    /**
     * 設定返回的響應包含HTTPS頭部資訊。
     */
    curl_setopt($curl, CURLOPT_HEADER, TRUE);
    /**
     * 發送HTTPS POST請求。
     */
    $response = curl_exec($curl);
    if ($response == FALSE) {
        print "curl_exec failed!\n";
        curl_close($curl);
        return ;
    }
    /**
     * 處理服務端返回的響應。
     */
    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    $bodyContent = substr($response, $headerSize);
    curl_close($curl);
    if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
        file_put_contents($audioSaveFile, $bodyContent);
        print "The POST request succeed!\n";
    }
    else {
        print "The POST request failed: " . $bodyContent . "\n";
    }
}
$appkey = "<appkey>";
$token = "<token>";
$text = "今天是周一,天氣挺好的。";
$textUrlEncode = urlencode($text);
$textUrlEncode = preg_replace('/\+/', '%20', $textUrlEncode);
$textUrlEncode = preg_replace('/\*/', '%2A', $textUrlEncode);
$textUrlEncode = preg_replace('/%7E/', '~', $textUrlEncode);
$audioSaveFile = "syAudio.wav";
$format = "wav";
$sampleRate = 16000;
processGETRequest($appkey, $token, $textUrlEncode, $audioSaveFile, $format, $sampleRate);
// processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate);
?>

Node.js

在樣本檔案所在目錄安裝依賴:

npm install request --save
const request = require('request');
const fs = require('fs');
function processGETRequest(appkey, token, text, audioSaveFile, format, sampleRate) {
    var url = 'https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts';
    /**
     * 設定URL請求參數。
     */
    url = url + '?appkey=' + appkey;
    url = url + '&token=' + token;
    url = url + '&text=' + text;
    url = url + '&format=' + format;
    url = url + '&sample_rate=' + sampleRate;
    // voice 發音人,可選,預設是xiaoyun。
    // url = url + "&voice=" + "xiaoyun";
    // volume 音量,範圍是0~100,可選,預設50。
    // url = url + "&volume=" + 50;
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // url = url + "&speech_rate=" + 0;
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // url = url + "&pitch_rate=" + 0;
    /**
     * 設定HTTPS GET請求。
     * encoding必須設定為null,HTTPS響應的Body為二進位Buffer類型。
     */
    var options = {
        url: url,
        method: 'GET',
        encoding: null
    };
    request(options, function (error, response, body) {
        /**
         * 處理服務端的響應。
         */
        if (error != null) {
            console.log(error);
        }
        else {
            var contentType = response.headers['content-type'];
            if (contentType === undefined || contentType != 'audio/mpeg') {
                console.log('The GET request failed!');
            }
            else {
                fs.writeFileSync(audioSaveFile, body);
                console.log('The GET request is succeed!');
            }
        }
    });
}
function processPOSTRequest(appkeyValue, tokenValue, textValue, audioSaveFile, formatValue, sampleRateValue) {
    var url = 'https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts';
    /**
     * 請求參數,以JSON格式字串填入HTTPS POST請求的Body中。
    */
    var task = {
        appkey : appkeyValue,
        token : tokenValue,
        text : textValue,
        format : formatValue,
        sample_rate : sampleRateValue
        // voice 發音人,可選,預設是xiaoyun。
        // voice : 'xiaoyun',
        // volume 音量,範圍是0~100,可選,預設50。
        // volume : 50,
        // speech_rate 語速,範圍是-500~500,可選,預設是0。
        // speech_rate : 0,
        // pitch_rate 語調,範圍是-500~500,可選,預設是0。
        // pitch_rate : 0
    };
    var bodyContent = JSON.stringify(task);
    /**
     * 設定HTTPS POST要求標頭部。
     */
    var httpHeaders = {
        'Content-type' : 'application/json'
    }
    /**
     * 設定HTTPS POST請求。
     * encoding必須設定為null,HTTPS響應的Body為二進位Buffer類型。
     */
    var options = {
        url: url,
        method: 'POST',
        headers: httpHeaders,
        body: bodyContent,
        encoding: null
    };
    request(options, function (error, response, body) {
        /**
         * 處理服務端的響應。
         */
        if (error != null) {
            console.log(error);
        }
        else {
            var contentType = response.headers['content-type'];
            if (contentType === undefined || contentType != 'audio/mpeg') {
                console.log('The POST request failed!');
            }
            else {
                fs.writeFileSync(audioSaveFile, body);
                console.log('The POST request is succeed!');
            }
        }
    });
}
var appkey = '<appkey>';
var token = '<token>';
var text = '今天是周一,天氣挺好的。';
var textUrlEncode = encodeURIComponent(text)
                    .replace(/[!'()*]/g, function(c) {
                        return '%' + c.charCodeAt(0).toString(16);
                    });
console.log(textUrlEncode);
var audioSaveFile = 'syAudio.wav';
var format = 'wav';
var sampleRate = 16000;
processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate);
// processPOSTRequest(appkey, token, text, audioSaveFile, format, sampleRate);

.NET

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Http;
using System.Web;
using Newtonsoft.Json.Linq;
namespace RESTfulAPI
{
    class SpeechSynthesizerRESTfulDemo
    {
        private string appkey;
        private string token;
        public SpeechSynthesizerRESTfulDemo(string appkey, string token)
        {
            this.appkey = appkey;
            this.token = token;
        }
        public void processGETRequest(string text, string audioSaveFile, string format, int sampleRate)
        {
            /**
             * 設定HTTPS GET請求:
             * 1.使用HTTPS協議
             * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
             * 3.語音合成介面請求路徑:/stream/v1/tts
             * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
             * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
             */
            string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
            url = url + "?appkey=" + appkey;
            url = url + "&token=" + token;
            url = url + "&text=" + text;
            url = url + "&format=" + format;
            url = url + "&sample_rate=" + sampleRate.ToString();
            // voice 發音人,可選,預設是xiaoyun。
            // url = url + "&voice=" + "xiaoyun";
            // volume 音量,範圍是0~100,可選,預設50。
            // url = url + "&volume=" + 50;
            // speech_rate 語速,範圍是-500~500,可選,預設是0。
            // url = url + "&speech_rate=" + 0;
            // pitch_rate 語調,範圍是-500~500,可選,預設是0。
            // url = url + "&pitch_rate=" + 0;
            /**
             * 發送HTTPS GET請求,處理服務端的響應。
             */
            HttpClient client = new HttpClient();
            HttpResponseMessage response = null;
            response = client.GetAsync(url).Result;
            string contentType = null;
            if (response.IsSuccessStatusCode)
            {
                string[] typesArray = response.Content.Headers.GetValues("Content-Type").ToArray();
                if (typesArray.Length > 0)
                {
                    contentType = typesArray.First();
                }
            }
            if ("audio/mpeg".Equals(contentType))
            {
                byte[] audioBuff = response.Content.ReadAsByteArrayAsync().Result;
                FileStream fs = new FileStream(audioSaveFile, FileMode.Create);
                fs.Write(audioBuff, 0, audioBuff.Length);
                fs.Flush();
                fs.Close();
                System.Console.WriteLine("The GET request succeed!");
            }
            else
            {
                // ContentType 為 null 或者為 "application/json"
                System.Console.WriteLine("Response status code and reason phrase: " +
                    response.StatusCode + " " + response.ReasonPhrase);
                string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
                System.Console.WriteLine("The GET request failed: " + responseBodyAsText);
            }
        }
        public void processPOSTRequest(string text, string audioSaveFile, string format, int sampleRate)
        {
            /**
             * 設定HTTPS POST請求:
             * 1.使用HTTPS協議
             * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
             * 3.語音合成介面請求路徑:/stream/v1/tts
             * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
             * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
             */
            string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
            JObject obj = new JObject();
            obj["appkey"] = appkey;
            obj["token"] = token;
            obj["text"] = text;
            obj["format"] = format;
            obj["sample_rate"] = sampleRate;
            // voice 發音人,可選,預設是xiaoyun。
            // obj["voice"] = "xiaoyun";
            // volume 音量,範圍是0~100,可選,預設50。
            // obj["volume"] = 50;
            // speech_rate 語速,範圍是-500~500,可選,預設是0。
            // obj["speech_rate"] = 0;
            // pitch_rate 語調,範圍是-500~500,可選,預設是0。
            // obj["pitch_rate"] = 0;
            String bodyContent = obj.ToString();
            StringContent content = new StringContent(bodyContent, Encoding.UTF8, "application/json");
            /**
             * 發送HTTPS POST請求,處理服務端的響應。
             */
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.PostAsync(url, content).Result;
            string contentType = null;
            if (response.IsSuccessStatusCode)
            {
                string[] typesArray = response.Content.Headers.GetValues("Content-Type").ToArray();
                if (typesArray.Length > 0)
                {
                    contentType = typesArray.First();
                }
            }
            if ("audio/mpeg".Equals(contentType))
            {
                byte[] audioBuff = response.Content.ReadAsByteArrayAsync().Result;
                FileStream fs = new FileStream(audioSaveFile, FileMode.Create);
                fs.Write(audioBuff, 0, audioBuff.Length);
                fs.Flush();
                fs.Close();
                System.Console.WriteLine("The POST request succeed!");
            }
            else
            {
                System.Console.WriteLine("Response status code and reason phrase: " +
                    response.StatusCode + " " + response.ReasonPhrase);
                string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
                System.Console.WriteLine("The POST request failed: " + responseBodyAsText);
            }
        }
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                System.Console.WriteLine("SpeechSynthesizerRESTfulDemo need params: <token> <app-key>");
                return;
            }
            string token = args[0];
            string appkey = args[1];
            SpeechSynthesizerRESTfulDemo demo = new SpeechSynthesizerRESTfulDemo(appkey, token);
            string text = "今天是周一,天氣挺好的。";
            // 採用RFC 3986規範進行urlencode編碼。
            string textUrlEncode = text;
            textUrlEncode = HttpUtility.UrlEncode(textUrlEncode, Encoding.UTF8)
                .Replace("+", "%20")
                .Replace("*", "%2A")
                .Replace("%7E", "~");
            System.Console.WriteLine(textUrlEncode);
            string audioSaveFile = "syAudio.wav";
            string format = "wav";
            int sampleRate = 16000;
            demo.processGETRequest(textUrlEncode, audioSaveFile, format, sampleRate);
            //demo.processPOSTRequest(text, audioSaveFile, format, sampleRate);
        }
    }
}

Go

package main
import (
    "fmt"
    "net/url"
    "net/http"
    "io/ioutil"
    "encoding/json"
    "strconv"
    "os"
    "bytes"
    "strings"
)
func processGETRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
    /**
     * 設定HTTPS GET請求:
     * 1.使用HTTPS協議
     * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
     * 3.語音合成介面請求路徑:/stream/v1/tts
     * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
     * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
     */
    var url string = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts"
    url = url + "?appkey=" + appkey
    url = url + "&token=" + token
    url = url + "&text=" + text
    url = url + "&format=" + format
    url = url + "&sample_rate=" + strconv.Itoa(sampleRate)
    // voice 發音人,可選,預設是xiaoyun。
    // url = url + "&voice=" + "xiaoyun"
    // volume 音量,範圍是0~100,可選,預設50。
    // url = url + "&volume=" + strconv.Itoa(50)
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // url = url + "&speech_rate=" + strconv.Itoa(0)
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // url = url + "&pitch_rate=" + strconv.Itoa(0)
    /**
     * 發送HTTPS GET請求,處理服務端的響應。
     */
    response, err := http.Get(url)
    if err != nil {
        fmt.Println("The GET request failed!")
        panic(err)
    }
    defer response.Body.Close()    
    contentType := response.Header.Get("Content-Type")
    body, _ := ioutil.ReadAll(response.Body)
    if ("audio/mpeg" == contentType) {
        file, _ := os.Create(audioSaveFile)
        defer file.Close()
        file.Write([]byte(body))
        fmt.Println("The GET request succeed!")
    } else {
        // ContentType 為 null 或者為 "application/json"
        statusCode := response.StatusCode
        fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
        fmt.Println("The GET request failed: " + string(body))
    }
}
func processPOSTRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
    /**
     * 設定HTTPS POST請求:
     * 1.使用HTTPS協議
     * 2.語音合成服務網域名稱:nls-gateway-ap-southeast-1.aliyuncs.com
     * 3.語音合成介面請求路徑:/stream/v1/tts
     * 4.設定本樣本使用的請求參數:appkey、token、text、format、sample_rate
     * 5.設定可選請求參數:voice、volume、speech_rate、pitch_rate
     */
    var url string = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts"
    bodyContent := make(map[string]interface{})
    bodyContent["appkey"] = appkey
    bodyContent["text"] = text
    bodyContent["token"] = token
    bodyContent["format"] = format
    bodyContent["sample_rate"] = sampleRate
    // voice 發音人,可選,預設是xiaoyun。
    // bodyContent["voice"] = "xiaoyun"
    // volume 音量,範圍是0~100,可選,預設50。
    // bodyContent["volume"] = 50
    // speech_rate 語速,範圍是-500~500,可選,預設是0。
    // bodyContent["speech_rate"] = 0
    // pitch_rate 語調,範圍是-500~500,可選,預設是0。
    // bodyContent["pitch_rate"] = 0
    bodyJson, err := json.Marshal(bodyContent)
    if err != nil {
        panic(nil)
    }
    /**
     * 發送HTTPS POST請求,處理服務端的響應。
     */
    response, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(bodyJson)))
    if err != nil {
        panic(err)
    }
    defer response.Body.Close()
    contentType := response.Header.Get("Content-Type")
    body, _ := ioutil.ReadAll(response.Body)
    if ("audio/mpeg" == contentType) {
        file, _ := os.Create(audioSaveFile)
        defer file.Close()
        file.Write([]byte(body))
        fmt.Println("The POST request succeed!")
    } else {
        // ContentType 為 null 或者為 "application/json"
        statusCode := response.StatusCode
        fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
        fmt.Println("The POST request failed: " + string(body))
    }    
}
func main() {
    var appkey string = "<appkey>"
    var token  string = "<token>"
    var text string = "今天是周一,天氣挺好的。"
    var textUrlEncode = text
    textUrlEncode = url.QueryEscape(textUrlEncode)
    textUrlEncode = strings.Replace(textUrlEncode, "+", "%20", -1)
    textUrlEncode = strings.Replace(textUrlEncode, "*", "%2A", -1)
    textUrlEncode = strings.Replace(textUrlEncode, "%7E", "~", -1)
    fmt.Println(textUrlEncode)
    var audioSaveFile string = "syAudio.wav"
    var format string = "wav"
    var sampleRate int = 16000
    processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate)
    // processPOSTRequest(appkey, token, text, audioSaveFile, format, sampleRate)
}

互動流程

用戶端發送包含文本的 GET 或 POST 請求,服務端在 HTTP 響應體中返迴音頻。流式用戶端應持續讀取響應體,直到本次響應結束。

請求參數

GET 請求將參數放在 URL 查詢串中;POST 請求將參數放在 JSON 請求體中。Token 也可以通過 X-NLS-Token 要求標頭傳入。

參數

類型

必選

說明

appkey

String

是

專案 AppKey。

text

String

是

待合成的文本,使用 UTF-8 編碼。GET 請求還需要按 RFC 3986 進行 URL 編碼;POST 請求不需要 URL 編碼。

token

String

否

Access Token。不設定此參數時,必須通過 X-NLS-Token 要求標頭傳入。

format

String

否

音頻格式,取值為小寫 pcm、wav 或 mp3。預設值:pcm。

sample_rate

Integer

否

音頻採樣率,單位為 Hz。支援 8000、16000,預設值:16000。預設發音人 xiaoyun 還支援 24000;其他發音人的支援範圍以對應說明為準。

voice

String

否

發音人。預設值:xiaoyun。發音人列表和支援範圍請參見介面說明。

volume

Integer

否

音量。取值範圍:0~100。預設值:50。

speech_rate

Integer

否

語速。取值範圍:-500~500。預設值:0。

pitch_rate

Integer

否

語調。取值範圍:-500~500。預設值:0。

chunk

Boolean

否

GET 流式樣本設定為 true,使用 HTTP Chunked 方式接收音頻。用戶端仍需分段讀取響應;不設定此參數時,響應也可能使用分塊傳輸。

GET 請求

將 text 進行 UTF-8 編碼後,再進行 URL 編碼。例如,+ 編碼為 %2B,* 編碼為 %2A,~ 保持不變。請求樣本如下,<appkey> 和 <token> 為佔位值:

https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts?appkey=<appkey>&token=<token>&text=%E4%BB%8A%E5%A4%A9%E6%98%AF%E5%91%A8%E4%B8%80%EF%BC%8C%E5%A4%A9%E6%B0%94%E6%8C%BA%E5%A5%BD%E7%9A%84%E3%80%82&format=wav&sample_rate=16000

也可以省略查詢串中的 token,改用要求標頭:

要求標頭

類型

必選

說明

X-NLS-Token

String

條件必選

查詢串中未設定 token 時必選。

POST 請求

使用 UTF-8 編碼的 JSON 請求體,text 不進行 URL 編碼。

要求標頭

類型

必選

說明

Content-Type

String

是

設定為 application/json。

X-NLS-Token

String

條件必選

請求體中未設定 token 時必選。

Content-Length

Long

否

請求體位元組數,通常由 HTTP 用戶端自動化佈建。

請求體樣本:

{
  "appkey": "<appkey>",
  "text": "今天是周一,天氣挺好的。",
  "token": "<token>",
  "format": "wav",
  "sample_rate": 16000
}

響應結果

GET 和 POST 使用相同的響應格式。結合 HTTP 狀態代碼和 Content-Type 判斷結果,不要把錯誤響應儲存為音頻。

成功響應

Content-Type 為 audio/mpeg,響應體為音頻位元據。該回應標頭不表示請求的音頻格式一定是 MP3;實際音頻格式由 format 決定。

成功響應可能不包含 X-NLS-RequestId。如果返回了該欄位,記錄其值用於排查問題。

失敗響應

Content-Type 為 application/json 時,響應體包含 JSON 錯誤資訊。Content-Type 缺失或不是預期的音訊類型時,也應按異常響應處理。

{
    "task_id":"8f95d0b9b6e948bc98e8d0ce64b0****",
    "result":"",
    "status":40000000,
    "message":"Gateway:CLIENT_ERROR:in post data, json format illegal"
}

欄位

類型

說明

task_id

String

請求任務 ID,通常為 32 位字串。

result

String

服務結果。

status

Integer

服務狀態代碼。

message

String

錯誤資訊。

記錄響應中的 X-NLS-RequestId 或 task_id、HTTP 狀態代碼和錯誤資訊。需要支援人員時,提供這些資訊,不要提供 Token。

服務狀態代碼

status 是 JSON 響應中的服務狀態代碼,與 HTTP 狀態代碼不同。

服務狀態代碼

含義

處理建議

20000000

請求成功

無。

40000000

用戶端錯誤

檢查錯誤資訊,必要時聯絡支援人員。

40000001

身份認證失敗

檢查 Token 是否正確、是否到期。

40000002

無效的訊息

檢查請求訊息格式。

40000003

無效的參數

檢查參數取值。

40000004

空閑逾時

檢查是否長時間未發送資料。

40000005

請求數量過多

檢查並發串連數和每秒請求數。

41020001

語音合成用戶端錯誤

根據 message 檢查合成參數。例如,音頻格式使用小寫 pcm、wav 或 mp3。

50000000

服務端錯誤

記錄錯誤資訊;重複出現時聯絡支援人員。

50000001

內部 GRPC 調用錯誤

記錄錯誤資訊;重複出現時聯絡支援人員。