All Products
Search
Document Center

RESTful API 2.0

Last Updated: Oct 24, 2019

Features

The speech synthesis RESTful API allows you to send HTTPS GET and POST requests to upload text to be synthesized to the server. Then, the server returns the speech synthesis result of the text. You must ensure that the connection with the server is uninterrupted before the speech synthesis result is returned. The speech synthesis RESTful API supports the following features:

  • Synthesizes the input into audio files in PCM, WAV, and MP3 formats.
  • Sets the sampling rates of the synthesized audio files to 8,000 Hz or 16,000 Hz.
  • Sets multiple speakers.
  • Sets the speed, intonation, and volume.

    Important notes

    To ensure constant improvement of the text-to-speech (TTS) synthesis effect, more and more complex algorithms are used. Therefore, the synthesis may take a longer time. In this case, we recommend that you use stream synthesis. For more information about the sample code of stream synthesis, see the Java demo in this topic.

Endpoints

Access type Description URL Host
External access from the Internet This endpoint allows you to access the speech synthesis service from any host over the Internet. https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts nls-gateway-ap-southeast-1.aliyuncs.com

This topic describes how to access the speech synthesis service over the Internet as an example. To use an ECS instance located to access the speech synthesis service over an internal network, use HTTP instead of HTTPS. In addition, replace the URL and host for Internet access with those for internal access. In this topic, all demos except the Python demo support both HTTP and HTTPS. Read the relevant notes before using the Python demo.

Interaction process

As shown in the following figure, the client sends an HTTPS GET or POST request containing the text to be synthesized to the server. Then, the server returns an HTTPS response containing the synthesized speech data.

RESTful interaction flowchart

Note: The server adds the task_id field to all responses to indicate the ID of the synthesis task. You need to record the value of this field. If an error occurs, you can open a ticket to submit the task ID and error message.

Request parameters

The following table lists the request parameters required for speech synthesis. If you send an HTTPS GET request, you must set the parameters in the HTTPS URL. If you send an HTTPS POST request, you must set the parameters in the HTTPS body.

Parameter Type Required Description
appkey String Yes The appkey of the application. For more information about how to obtain the appkey, see Create a project.
text String Yes The text to be synthesized, which must be UTF-8 encoded. If you send an HTTPS GET request, you must encode the URL based on the RFC 3986 standard. For example, encode a plus sign (+) as %2B. You do not need to encode the URL if you send an HTTPS POST request.
token String No The service authentication token. For more information about how to obtain the token, see Obtain a token. If you do not set this parameter, you must set the X-NLS-Token field in the HTTPS header to specify the token.
format String No The audio coding format. Valid values: pcm, wav, and mp3. Default value: pcm.
sample_rate Integer No The audio sampling rate, in Hz. Valid values: 16000 and 8000. Default value: 16000.
voice String No The speaker. Default value: xiaoyun. For more information about other available speakers, see Overview.
volume Integer No The volume. Value range: 0 to 100. Default value: 50.
speech_rate Integer No The speed. Value range: -500 to 500. Default value: 0.
pitch_rate Integer No The intonation. Value range: -500 to 500. Default value: 0.

Text upload by using the GET method

A complete GET request of the speech synthesis RESTful API contains the following elements:

1. URL

Protocol URL Method
HTTPS https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts GET

2. Request parameters

See the preceding request parameter table.

The complete request link composed of the preceding URL and request parameters is as follows. You can open this link in a browser to obtain the speech synthesis result.

  1. # Enter the appkey of the project that you create in the console and your token. Open the link in a browser to obtain the speech synthesis result.
  2. # The text content is "Today is Monday. It is a fine day."
  3. https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts?appkey=${Your appkey}&token=${Your 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

3. HTTPS GET request header

Parameter Type Required Description
X-NLS-Token String No The service authentication token. For more information about how to obtain the token, see Obtain a token. You must set this field if you do not set the token parameter in the request parameters.

Notes:

  • You can specify the service authentication token by setting either the token parameter in the request parameters or the X-NLS-Token field in the HTTPS header. We recommend that you set the token parameter in the request parameters.
  • You must encode the text parameter in UTF-8 format, and then encode the URL based on the RFC 3986 standard. For example, you must encode a plus sign (+) as %2B, an asterisk (*) as %2A, and %7E as a tilde (~).

Text upload by using the POST method

A complete POST request of the speech synthesis RESTful API contains the following elements:

1. URL

Protocol URL Method
HTTPS https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts POST

2. HTTPS POST request header

Parameter Type Required Description
X-NLS-Token String No The service authentication token. For more information about how to obtain the token, see Obtain a token. You must set this field if you do not set the token parameter in the request parameters of the HTTPS request body.
Content-Type String Yes The content type. Fixed value: application/json, which indicates that the content of the HTTPS request body is a JSON string.
Content-Length Long No The length of content of the HTTPS request body.

3. HTTPS POST request body

The HTTPS POST request body is a JSON string consisting of request parameters. Therefore, you must set the Content-Type parameter in the HTTPS POST request header to application/json. Examples:

  1. {
  2. "appkey":"31f932fb",
  3. "text":"Today is Monday. It is a fine day.",
  4. "token":"45034**********3c793",
  5. "format":"wav"
  6. }

Notes:

  • You can specify the service authentication token by setting either the token parameter in the request body or the X-NLS-Token field in the HTTPS header. We recommend that you set the token parameter in the request body.
  • When sending an HTTPS POST request, you must encode the text parameter in the request body in UTF-8 format. However, you do not need to encode the URL, which is different from sending an HTTPS GET request.

Response

The responses to an HTTPS GET request and an HTTPS POST request are the same. The response is included in the HTTPS body. Whether a response succeeds or fails depends on the value of the Content-Type field in the HTTPS header.

  • Sample success response

    • If the synthesis is successful, the value of the Content-Type field in the HTTPS response header is audio/mpeg, and the synthesized speech data is included in the response body.
    • The value of the X-NLS-RequestId field in the HTTPS response header is the ID of the request task, which can be used for debugging and troubleshooting.
    • The content of the response body is the binary data of the synthesized audio file.
  • Sample error response

    • If the synthesis fails, the HTTPS response header does not contain the Content-Type field or the value of the Content-Type field is application/json. The response body includes the error message.
    • The value of the X-NLS-RequestId field in the HTTPS response header is the ID of the request task, which can be used for debugging and troubleshooting.
    • The response body includes the error message, which is a JSON string. Example:
  1. {
  2. "task_id":"8f95d0b9b6e948bc98e8d0ce64b0cf57",
  3. "result":"",
  4. "status":40000000,
  5. "message":"Gateway:CLIENT_ERROR:in post data, json format illegal"
  6. }

Response fields

The following table describes the fields in the error message of the response.

Parameter Type Description
task_id String The 32-bit task ID. Record this value for troubleshooting.
result String The service result.
status Integer The service status code.
message String The service status description.

Service status codes

Service status code Service status description Solution
20000000 The request is successful.
40000000 The error message returned because a client error has occurred. This is the default client error code. Resolve the error according to the error message or open a ticket.
40000001 The error message returned because the client fails authentication. Check whether the token used by the client is correct and valid.
40000002 The error message returned because the message is invalid. Check whether the message sent by the client meets relevant requirements.
40000003 The error message returned because the parameter value is invalid. Check whether the parameter value is correct.
40000004 The error message returned because the idle status of the client times out. Check whether the client does not send any data to the server for a long time.
40000005 The error message returned because the number of requests exceeds the upper limit. Check whether the number of concurrent connections or the queries per second (QPS) exceeds the upper limit.
50000000 The error message returned because a server error has occurred. This is the default server error code. If the error code is occasionally returned, ignore it. If the error code is returned multiple times, open a ticket.
50000001 The error message returned because an internal gRPC call error has occurred. If the error code is occasionally returned, ignore it. If the error code is returned multiple times, open a ticket.

Java demo

Dependencies:

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>3.9.1</version>
  5. </dependency>
  6. <!-- http://mvnrepository.com/artifact/com.alibaba/fastjson -->
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.42</version>
  11. </dependency>

Sample code:

  1. package com.alibaba.nls.client.example;
  2. import com.alibaba.fastjson.JSONObject;
  3. import okhttp3.*;
  4. import java.io.*;
  5. import java.net.URLEncoder;
  6. public class SpeechSynthesizerRESTfulDemo {
  7. private String accessToken;
  8. private String appkey;
  9. public SpeechSynthesizerRESTfulDemo(String appkey, String token) {
  10. this.appkey = appkey;
  11. this.accessToken = token;
  12. }
  13. /**
  14. * HTTPS GET request
  15. */
  16. public void processGETRequet(String text, String audioSaveFile, String format, int sampleRate) {
  17. /**
  18. * Set the HTTPS GET request.
  19. * 1. Use HTTPS.
  20. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  21. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  22. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  23. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  24. */
  25. String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  26. url = url + "?appkey=" + appkey;
  27. url = url + "&token=" + accessToken;
  28. url = url + "&text=" + text;
  29. url = url + "&format=" + format;
  30. url = url + "&sample_rate=" + String.valueOf(sampleRate);
  31. // voice Optional. The speaker. Default value: xiaoyun.
  32. // url = url + "&voice=" + "xiaoyun";
  33. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  34. // url = url + "&volume=" + String.valueOf(50);
  35. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  36. // url = url + "&speech_rate=" + String.valueOf(0);
  37. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  38. // url = url + "&pitch_rate=" + String.valueOf(0);
  39. System.out.println("URL: " + url);
  40. /**
  41. * Send the HTTPS GET request and process the response returned by the server.
  42. */
  43. Request request = new Request.Builder()
  44. .url(url)
  45. .get()
  46. .build();
  47. try {
  48. OkHttpClient client = new OkHttpClient();
  49. Response response = client.newCall(request).execute();
  50. String contentType = response.header("Content-Type");
  51. if ("audio/mpeg".equals(contentType)) {
  52. File f = new File(audioSaveFile);
  53. FileOutputStream fout = new FileOutputStream(f);
  54. fout.write(response.body().bytes());
  55. fout.close();
  56. System.out.println("The GET request succeed!");
  57. }
  58. else {
  59. // The value of Content-Type is null or application/json.
  60. String errorMessage = response.body().string();
  61. System.out.println("The GET request failed: " + errorMessage);
  62. }
  63. response.close();
  64. } catch (Exception e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. /**
  69. * HTTPS POST request
  70. */
  71. public void processPOSTRequest(String text, String audioSaveFile, String format, int sampleRate) {
  72. /**
  73. * Set the HTTPS POST request.
  74. * 1. Use HTTPS.
  75. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  76. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  77. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  78. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  79. */
  80. String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  81. JSONObject taskObject = new JSONObject();
  82. taskObject.put("appkey", appkey);
  83. taskObject.put("token", accessToken);
  84. taskObject.put("text", text);
  85. taskObject.put("format", format);
  86. taskObject.put("sample_rate", sampleRate);
  87. // voice Optional. The speaker. Default value: xiaoyun.
  88. // taskObject.put("voice", "xiaoyun");
  89. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  90. // taskObject.put("volume", 50);
  91. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  92. // taskObject.put("speech_rate", 0);
  93. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  94. // taskObject.put("pitch_rate", 0);
  95. String bodyContent = taskObject.toJSONString();
  96. System.out.println("POST Body Content: " + bodyContent);
  97. RequestBody reqBody = RequestBody.create(MediaType.parse("application/json"), bodyContent);
  98. Request request = new Request.Builder()
  99. .url(url)
  100. .header("Content-Type", "application/json")
  101. .post(reqBody)
  102. .build();
  103. try {
  104. OkHttpClient client = new OkHttpClient();
  105. Response response = client.newCall(request).execute();
  106. String contentType = response.header("Content-Type");
  107. if ("audio/mpeg".equals(contentType)) {
  108. File f = new File(audioSaveFile);
  109. FileOutputStream fout = new FileOutputStream(f);
  110. fout.write(response.body().bytes());
  111. fout.close();
  112. System.out.println("The POST request succeed!");
  113. }
  114. else {
  115. // The value of Content-Type is null or application/json.
  116. String errorMessage = response.body().string();
  117. System.out.println("The POST request failed: " + errorMessage);
  118. }
  119. response.close();
  120. } catch (Exception e) {
  121. e.printStackTrace();
  122. }
  123. }
  124. public static void main(String[] args) {
  125. if (args.length < 2) {
  126. System.err.println("SpeechSynthesizerRESTfulDemo need params: <token> <app-key>");
  127. System.exit(-1);
  128. }
  129. String token = args[0];
  130. String appkey = args[1];
  131. SpeechSynthesizerRESTfulDemo demo = new SpeechSynthesizerRESTfulDemo(appkey, token);
  132. String text = "Today is Monday. It is a fine day." ;
  133. // Encode the URL based on the RFC 3986 standard.
  134. String textUrlEncode = text;
  135. try {
  136. textUrlEncode = URLEncoder.encode(textUrlEncode, "UTF-8")
  137. .replace("+", "%20")
  138. .replace("*", "%2A")
  139. .replace("%7E", "~");
  140. } catch (UnsupportedEncodingException e) {
  141. e.printStackTrace();
  142. }
  143. System.out.println(textUrlEncode);
  144. String audioSaveFile = "syAudio.wav";
  145. String format = "wav";
  146. int sampleRate = 16000;
  147. demo.processGETRequet(textUrlEncode, audioSaveFile, format, sampleRate);
  148. //demo.processPOSTRequest(text, audioSaveFile, format, sampleRate);
  149. }
  150. }

Java demo of stream synthesis

  1. package com.alibaba.nls.restful;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.util.concurrent.CountDownLatch;
  7. import io.netty.handler.codec.http.HttpHeaders;
  8. import org.asynchttpclient.AsyncHandler;
  9. import org.asynchttpclient.AsyncHttpClient;
  10. import org.asynchttpclient.AsyncHttpClientConfig;
  11. import org.asynchttpclient.DefaultAsyncHttpClient;
  12. import org.asynchttpclient.DefaultAsyncHttpClientConfig;
  13. import org.asynchttpclient.HttpResponseBodyPart;
  14. import org.asynchttpclient.HttpResponseStatus;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. /**
  18. * This demo shows how to enable HTTP chunked transfer encoding when the speech synthesis RESTful API is called.
  19. */
  20. public class SpeechSynthesizerRestfulChunkedDemo {
  21. private static Logger logger = LoggerFactory.getLogger(SpeechSynthesizerRestfulChunkedDemo.class);
  22. private String accessToken;
  23. private String appkey;
  24. public SpeechSynthesizerRestfulChunkedDemo(String appkey, String token) {
  25. this.appkey = appkey;
  26. this.accessToken = token;
  27. }
  28. public void processGETRequet(String text, String audioSaveFile, String format, int sampleRate, String voice, boolean chunked) {
  29. /**
  30. * Set the HTTPS GET request.
  31. * 1. Use HTTPS.
  32. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  33. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  34. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  35. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  36. */
  37. String url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  38. url = url + "?appkey=" + appkey;
  39. url = url + "&token=" + accessToken;
  40. url = url + "&text=" + text;
  41. url = url + "&format=" + format;
  42. url = url + "&voice=" + "siyue";
  43. url = url + "&sample_rate=" + String.valueOf(sampleRate);
  44. url = url + "&chunk=" + String.valueOf(chunked);
  45. // voice Optional. The speaker. Default value: xiaoyun.
  46. // url = url + "&voice=" + "xiaoyun";
  47. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  48. // url = url + "&volume=" + String.valueOf(50);
  49. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  50. // url = url + "&speech_rate=" + String.valueOf(0);
  51. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  52. // url = url + "&pitch_rate=" + String.valueOf(0);
  53. System.out.println("URL: " + url);
  54. try {
  55. AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
  56. .setConnectTimeout(1000)
  57. .setKeepAlive(true)
  58. .setReadTimeout(10000)
  59. .setRequestTimeout(50000)
  60. .setMaxConnections(1000)
  61. .setMaxConnectionsPerHost(200)
  62. .setPooledConnectionIdleTimeout(-1)
  63. .build();
  64. AsyncHttpClient httpClient = new DefaultAsyncHttpClient(config);
  65. CountDownLatch latch = new CountDownLatch(1);
  66. AsyncHandler<org.asynchttpclient.Response> handler = new AsyncHandler<org.asynchttpclient.Response>() {
  67. FileOutputStream outs;
  68. boolean firstRecvBinary = true;
  69. long startTime = System.currentTimeMillis();
  70. @Override
  71. public State onStatusReceived(HttpResponseStatus httpResponseStatus) throws Exception {
  72. logger.info("status {}", httpResponseStatus);
  73. if (httpResponseStatus.getStatusCode() != 200) {
  74. //logger.error("id {} status {}", id,httpResponseStatus);
  75. }
  76. return null;
  77. }
  78. @Override
  79. public State onHeadersReceived(HttpHeaders httpHeaders) throws Exception {
  80. logger.info("recv header {}", httpHeaders);
  81. outs = new FileOutputStream(new File("tts.wav"));
  82. return null;
  83. }
  84. @Override
  85. public State onBodyPartReceived(HttpResponseBodyPart httpResponseBodyPart) throws Exception {
  86. // TODO Important note: Once receiving a data stream, the server plays it to the user or processes it to improve the response speed.
  87. // TODO Do not perform time-consuming operations on this callback. You can push binary TTS voice streams asynchronously or in queue mode to another thread.
  88. logger.info("onBodyPartReceived " + httpResponseBodyPart.getBodyPartBytes());
  89. if (firstRecvBinary) {
  90. firstRecvBinary = false;
  91. // Note: The first packet latency includes the time consumed for establishing a network connection.
  92. logger.info("tts first latency " + (System.currentTimeMillis() - startTime) + " ms");
  93. }
  94. // In this example, save the voice streams to a file.
  95. outs.write(httpResponseBodyPart.getBodyPartBytes());
  96. return null;
  97. }
  98. @Override
  99. public void onThrowable(Throwable throwable) {
  100. logger.error("throwable {}", throwable);
  101. latch.countDown();
  102. }
  103. @Override
  104. public org.asynchttpclient.Response onCompleted() throws Exception {
  105. logger.info("completed");
  106. logger.info("tts total latency " + (System.currentTimeMillis() - startTime) + " ms");
  107. outs.close();
  108. latch.countDown();
  109. return null;
  110. }
  111. };
  112. httpClient.prepareGet(url).execute(handler);
  113. // Wait until the synthesis is completed.
  114. latch.await();
  115. }catch (Exception e) {
  116. }
  117. }
  118. public static void main(String[] args) {
  119. if (args.length < 2) {
  120. System.err.println("SpeechSynthesizerRestfulDemo need params: <token> <app-key>");
  121. System.exit(-1);
  122. }
  123. String token = args[0];
  124. String appkey = args[1];
  125. SpeechSynthesizerRestfulChunkedDemo demo = new SpeechSynthesizerRestfulChunkedDemo(appkey, token);
  126. String text = "Today is Monday. It is a fine day. I want to make a trip. Would you like to go with me?";
  127. // Encode the URL based on the RFC 3986 standard.
  128. String textUrlEncode = text;
  129. try {
  130. textUrlEncode = URLEncoder.encode(textUrlEncode, "UTF-8")
  131. .replace("+", "%20")
  132. .replace("*", "%2A")
  133. .replace("%7E", "~");
  134. } catch (UnsupportedEncodingException e) {
  135. e.printStackTrace();
  136. }
  137. System.out.println(textUrlEncode);
  138. String audioSaveFile = "syAudio.wav";
  139. String format = "wav";
  140. int sampleRate = 16000;
  141. // TODO Note: If the value of the last parameter is true, HTTP chunked transfer encoding is enabled.
  142. demo.processGETRequet(textUrlEncode, audioSaveFile, format, sampleRate, "siyue", true);
  143. System.out.println("### Game Over ###");
  144. }
  145. }

C++ demo

The C++ demo uses the third-party library cURL to process HTTPS requests and responses, and uses JsonCpp to set the JSON string in the POST request body. Click here to download the demo.

Directory description:

  • CMakeLists.txt: the CMakeList file of the demo project.
  • demo
File name Description
restfulTtsDemo.cpp The demo of the speech synthesis RESTful API.
  • include
Directory name Description
curl The header file directory of the cURL library.
json The header file directory of the JsonCpp library.
  • lib: the library, which contains the cURL dynamic library and JsonCpp dynamic library. Depending on the operating system, you can select the version for Linux (runtime environment: glibc 2.5 or later, and GCC 4 or GCC 5), or the version for Windows (runtime environment: Visual Studio 2013 or Visual Studio 2015).
  • readme.txt: the description.
  • release.log: the release notes.
  • version: the version number.
  • build.sh: the demo compilation script.

Notes:

  1. In Linux, the minimum runtime environment requirements are as follows: glibc 2.5 or later, and GCC 4 or GCC 5.
  2. The token is valid for 24 hours by default. If the token is invalid, obtain the token again. Otherwise, the request fails.
  3. In Windows, you need to build your own demo project.

Compilation and running:

  1. 1. Check whether you have installed CMake 2.4 or later on your local host.
  2. 2. cd path/to/sdk/lib
  3. 3. tar -zxvpf linux.tar.gz
  4. 4. cd path/to/sdk
  5. 5. Run the [./build.sh] command to compile the demo.
  6. 6. After compilation, go to the demo directory and run the [./restfulTtsDemo <your-token> <your-appkey>] command.
  7. If the operating system does not support CMake, you can run the following commands to manually compile the demo:
  8. 1: cd path/to/sdk/lib
  9. 2: tar -zxvpf linux.tar.gz
  10. 3: cd path/to/sdk/demo
  11. 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
  12. 5: export LD_LIBRARY_PATH=path/to/sdk/lib/linux/
  13. 6: ./restfulTtsDemo your-token your-appkey
  14. In Windows, you need to build your own demo project.

Sample code:

  1. #ifdef _WIN32
  2. #include <Windows.h>
  3. #endif
  4. #include <iostream>
  5. #include <string>
  6. #include <map>
  7. #include <fstream>
  8. #include <sstream>
  9. #include "curl/curl.h"
  10. #include "json/json.h"
  11. using namespace std;
  12. #ifdef _WIN32
  13. string GBKToUTF8(const string &strGBK) {
  14. string strOutUTF8 = "";
  15. WCHAR * str1;
  16. int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
  17. str1 = new WCHAR[n];
  18. MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
  19. n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
  20. char * str2 = new char[n];
  21. WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
  22. strOutUTF8 = str2;
  23. delete[] str1;
  24. str1 = NULL;
  25. delete[] str2;
  26. str2 = NULL;
  27. return strOutUTF8;
  28. }
  29. #endif
  30. void stringReplace(string& src, const string& s1, const string& s2) {
  31. string::size_type pos = 0;
  32. while ((pos = src.find(s1, pos)) != string::npos) {
  33. src.replace(pos, s1.length(), s2);
  34. pos += s2.length();
  35. }
  36. }
  37. string urlEncode(const string& src) {
  38. CURL* curl = curl_easy_init();
  39. char* output = curl_easy_escape(curl, src.c_str(), src.size());
  40. string result(output);
  41. curl_free(output);
  42. curl_easy_cleanup(curl);
  43. return result;
  44. }
  45. size_t responseHeadersCallback(void* ptr, size_t size, size_t nmemb, void* userdata)
  46. {
  47. map<string, string> *headers = (map<string, string>*)userdata;
  48. string line((char*)ptr);
  49. string::size_type pos = line.find(':');
  50. if (pos != line.npos)
  51. {
  52. string name = line.substr(0, pos);
  53. string value = line.substr(pos + 2);
  54. size_t p = 0;
  55. if ((p = value.rfind('\r')) != value.npos) {
  56. value = value.substr(0, p);
  57. }
  58. headers->insert(make_pair(name, value));
  59. }
  60. return size * nmemb;
  61. }
  62. size_t responseBodyCallback(void* ptr, size_t size, size_t nmemb, void* userData) {
  63. size_t len = size * nmemb;
  64. char* pBuf = (char*)ptr;
  65. string* bodyContent = (string*)userData;
  66. (*bodyContent).append(string(pBuf, pBuf + len));
  67. return len;
  68. }
  69. int processGETRequest(string appKey, string token, string text,
  70. string audioSaveFile, string format, int sampleRate) {
  71. CURL* curl = NULL;
  72. CURLcode res;
  73. curl = curl_easy_init();
  74. if (curl == NULL) {
  75. return -1;
  76. }
  77. string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  78. /**
  79. * Set the HTTPS URL request parameters.
  80. */
  81. ostringstream oss;
  82. oss << url;
  83. oss << "?appkey=" << appKey;
  84. oss << "&token=" << token;
  85. oss << "&text=" << text;
  86. oss << "&format=" << format;
  87. oss << "&sample_rate=" << sampleRate;
  88. // voice Optional. The speaker. Default value: xiaoyun.
  89. // oss << "&voice=" << "xiaoyun";
  90. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  91. // oss << "&volume=" << 50;
  92. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  93. // oss << "&speech_rate=" << 0;
  94. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  95. // oss << "&pitch_rate=" << 0;
  96. string request = oss.str();
  97. cout << request << endl;
  98. curl_easy_setopt(curl, CURLOPT_URL, request.c_str());
  99. /**
  100. * Set the HTTPS header callback function for receiving the response.
  101. */
  102. map<string, string> responseHeaders;
  103. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, responseHeadersCallback);
  104. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders);
  105. /**
  106. * Set the HTTPS body callback function for receiving the response.
  107. */
  108. string bodyContent = "";
  109. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseBodyCallback);
  110. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyContent);
  111. /**
  112. * Send the HTTPS GET request.
  113. */
  114. res = curl_easy_perform(curl);
  115. /**
  116. * Release the resource.
  117. */
  118. curl_easy_cleanup(curl);
  119. if (res != CURLE_OK) {
  120. cerr << "curl_easy_perform failed: " << curl_easy_strerror(res) << endl;
  121. return -1;
  122. }
  123. /**
  124. * Process the response returned by the server.
  125. */
  126. map<string, string>::iterator it = responseHeaders.find("Content-Type");
  127. if (it != responseHeaders.end() && it->second.compare("audio/mpeg") == 0) {
  128. ofstream fs;
  129. fs.open(audioSaveFile.c_str(), ios::out | ios::binary);
  130. if (!fs.is_open()) {
  131. cout << "The audio save file can not open!";
  132. return -1;
  133. }
  134. fs.write(bodyContent.c_str(), bodyContent.size());
  135. fs.close();
  136. cout << "The GET request succeed!" << endl;
  137. }
  138. else {
  139. cout << "The GET request failed: " + bodyContent << endl;
  140. return -1;
  141. }
  142. return 0;
  143. }
  144. int processPOSTRequest(string appKey, string token, string text,
  145. string audioSaveFile, string format, int sampleRate) {
  146. CURL* curl = NULL;
  147. CURLcode res;
  148. curl = curl_easy_init();
  149. if (curl == NULL) {
  150. return -1;
  151. }
  152. string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  153. /**
  154. * Set the HTTPS POST URL.
  155. */
  156. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  157. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  158. /**
  159. * Set the HTTPS POST request header.
  160. */
  161. struct curl_slist* headers = NULL;
  162. // Content-Type
  163. headers = curl_slist_append(headers, "Content-Type:application/json");
  164. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  165. /**
  166. * Set the HTTPS POST request body.
  167. */
  168. Json::Value root;
  169. Json::FastWriter writer;
  170. root["appkey"] = appKey;
  171. root["token"] = token;
  172. root["text"] = text;
  173. root["format"] = format;
  174. root["sample_rate"] = sampleRate;
  175. // voice Optional. The speaker. Default value: xiaoyun.
  176. // root["voice"] = "xiaoyun";
  177. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  178. // root["volume"] = 50;
  179. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  180. // root["speech_rate"] = 0;
  181. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  182. // root["pitch_rate"] = 0;
  183. string task = writer.write(root);
  184. cout << "POST request Body: " << task << endl;
  185. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, task.c_str());
  186. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, task.length());
  187. /**
  188. * Set the HTTPS header callback function for receiving the response.
  189. */
  190. map<string, string> responseHeaders;
  191. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, responseHeadersCallback);
  192. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &responseHeaders);
  193. /**
  194. * Set the HTTPS body callback function for receiving the response.
  195. */
  196. string bodyContent = "";
  197. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseBodyCallback);
  198. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bodyContent);
  199. /**
  200. * Send the HTTPS POST request.
  201. */
  202. res = curl_easy_perform(curl);
  203. /**
  204. * Release the resource.
  205. */
  206. curl_slist_free_all(headers);
  207. curl_easy_cleanup(curl);
  208. if (res != CURLE_OK) {
  209. cerr << "curl_easy_perform failed: " << curl_easy_strerror(res) << endl;
  210. return -1;
  211. }
  212. /**
  213. * Process the response returned by the server.
  214. */
  215. map<string, string>::iterator it = responseHeaders.find("Content-Type");
  216. if (it != responseHeaders.end() && it->second.compare("audio/mpeg") == 0) {
  217. ofstream fs;
  218. fs.open(audioSaveFile.c_str(), ios::out | ios::binary);
  219. if (!fs.is_open()) {
  220. cout << "The audio save file can not open!";
  221. return -1;
  222. }
  223. fs.write(bodyContent.c_str(), bodyContent.size());
  224. fs.close();
  225. cout << "The POST request succeed!" << endl;
  226. }
  227. else {
  228. cout << "The POST request failed: " + bodyContent << endl;
  229. return -1;
  230. }
  231. return 0;
  232. }
  233. int main(int argc, char* argv[]) {
  234. if (argc < 3) {
  235. cerr << "params is not valid. Usage: ./demo your_token your_appkey" << endl;
  236. return -1;
  237. }
  238. string token = argv[1];
  239. string appKey = argv[2];
  240. string text = "Today is Monday. It is a fine day." ;
  241. #ifdef _WIN32
  242. text = GBKToUTF8(text);
  243. #endif
  244. string textUrlEncode = urlEncode(text);
  245. stringReplace(textUrlEncode, "+", "%20");
  246. stringReplace(textUrlEncode, "*", "%2A");
  247. stringReplace(textUrlEncode, "%7E", "~");
  248. string audioSaveFile = "syAudio.wav";
  249. string format = "wav";
  250. int sampleRate = 16000;
  251. // The demo is initialized only once.
  252. curl_global_init(CURL_GLOBAL_ALL);
  253. processGETRequest(appKey, token, textUrlEncode, audioSaveFile, format, sampleRate);
  254. //processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate);
  255. curl_global_cleanup();
  256. return 0;
  257. }

Python demo

Notes:

  1. Use the httplib module for Python 2.x, and use the http.client module for Python 3.x.
  2. Encode the URL based on the RFC 3986 standard. Use urllib.quote of the urllib module for Python 2.x, and use urllib.parse.quote_plus of the urllib.parse module for Python 3.x.
  3. If you access the service by using an internal access URL, you must use HTTP and replace HTTPSConnection with HTTPConnection.
  1. # Use the httplib module for Python 2.x.
  2. # conn = httplib.HTTPConnection(host)
  3. # Use the http.client module for Python 3.x.
  4. conn = http.client.HTTPConnection(host)

Example:

  1. # -*- coding: UTF-8 -*-
  2. # Import the httplib module for Python 2.x.
  3. # import httplib
  4. # Import the http.client module for Python 3.x.
  5. import http.client
  6. # Import the urllib module for Python 2.x.
  7. # import urllib
  8. # Import the urllib.parse module for Python 3.x.
  9. import urllib.parse
  10. import json
  11. def processGETRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
  12. host = 'nls-gateway-ap-southeast-1.aliyuncs.com'
  13. url = 'https://' + host + '/stream/v1/tts'
  14. # Set the URL request parameters.
  15. url = url + '?appkey=' + appKey
  16. url = url + '&token=' + token
  17. url = url + '&text=' + text
  18. url = url + '&format=' + format
  19. url = url + '&sample_rate=' + str(sampleRate)
  20. # voice Optional. The speaker. Default value: xiaoyun.
  21. # url = url + '&voice=' + 'xiaoyun'
  22. # volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  23. # url = url + '&volume=' + str(50)
  24. # speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  25. # url = url + '&speech_rate=' + str(0)
  26. # pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  27. # url = url + '&pitch_rate=' + str(0)
  28. print(url)
  29. # Use the httplib module for Python 2.x.
  30. # conn = httplib.HTTPSConnection(host)
  31. # Use the http.client module for Python 3.x.
  32. conn = http.client.HTTPSConnection(host)
  33. conn.request(method='GET', url=url)
  34. # Process the response returned by the server.
  35. response = conn.getresponse()
  36. print('Response status and response reason:')
  37. print(response.status ,response.reason)
  38. contentType = response.getheader('Content-Type')
  39. print(contentType)
  40. body = response.read()
  41. if 'audio/mpeg' == contentType :
  42. with open(audioSaveFile, mode='wb') as f:
  43. f.write(body)
  44. print('The GET request succeed!')
  45. else :
  46. print('The GET request failed: ' + str(body))
  47. conn.close()
  48. def processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate) :
  49. host = 'nls-gateway-ap-southeast-1.aliyuncs.com'
  50. url = 'https://' + host + '/stream/v1/tts'
  51. # Set the HTTPS header.
  52. httpHeaders = {
  53. 'Content-Type': 'application/json'
  54. }
  55. # Set the HTTPS body.
  56. body = {'appkey': appKey, 'token': token, 'text': text, 'format': format, 'sample_rate': sampleRate}
  57. body = json.dumps(body)
  58. print('The POST request body content: ' + body)
  59. # Use the httplib module for Python 2.x.
  60. # conn = httplib.HTTPSConnection(host)
  61. # Use the http.client module for Python 3.x.
  62. conn = http.client.HTTPSConnection(host)
  63. conn.request(method='POST', url=url, body=body, headers=httpHeaders)
  64. # Process the response returned by the server.
  65. response = conn.getresponse()
  66. print('Response status and response reason:')
  67. print(response.status ,response.reason)
  68. contentType = response.getheader('Content-Type')
  69. print(contentType)
  70. body = response.read()
  71. if 'audio/mpeg' == contentType :
  72. with open(audioSaveFile, mode='wb') as f:
  73. f.write(body)
  74. print('The POST request succeed!')
  75. else :
  76. print('The POST request failed: ' + str(body))
  77. conn.close()
  78. appKey = 'Your appkey'
  79. token = 'Your token'
  80. text = 'Today is Monday. It is a fine day.'
  81. # Encode the URL based on the RFC 3986 standard.
  82. textUrlencode = text
  83. # Use urllib.quote for Python 2.x.
  84. # textUrlencode = urllib.quote(textUrlencode, '')
  85. # Use urllib.parse.quote_plus for Python 3.x.
  86. textUrlencode = urllib.parse.quote_plus(textUrlencode)
  87. textUrlencode = textUrlencode.replace("+", "%20")
  88. textUrlencode = textUrlencode.replace("*", "%2A")
  89. textUrlencode = textUrlencode.replace("%7E", "~")
  90. print('text: ' + textUrlencode)
  91. audioSaveFile = 'syAudio.wav'
  92. format = 'wav'
  93. sampleRate = 16000
  94. # GET request
  95. processGETRequest(appKey, token, textUrlencode, audioSaveFile, format, sampleRate)
  96. # POST request
  97. # processPOSTRequest(appKey, token, text, audioSaveFile, format, sampleRate)

PHP demo

Note: The PHP demo uses cURL functions. Ensure that you have installed PHP 4.0.2 or later and cURL extensions.

  1. <?php
  2. function processGETRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate) {
  3. $url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  4. $url = $url . "?appkey=" . $appkey;
  5. $url = $url . "&token=" . $token;
  6. $url = $url . "&text=" . $text;
  7. $url = $url . "&format=" . $format;
  8. $url = $url . "&sample_rate=" . strval($sampleRate);
  9. // voice Optional. The speaker. Default value: xiaoyun.
  10. // $url = $url . "&voice=" . "xiaoyun";
  11. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  12. // $url = $url . "&volume=" . strval(50);
  13. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  14. // $url = $url . "&speech_rate=" . strval(0);
  15. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  16. // $url = $url . "&pitch_rate=" . strval(0);
  17. print $url . "\n";
  18. $curl = curl_init();
  19. curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  20. /**
  21. * Set the HTTPS GET URL.
  22. */
  23. curl_setopt($curl, CURLOPT_URL, $url);
  24. /**
  25. * Set the HTTPS header in the response.
  26. */
  27. curl_setopt($curl, CURLOPT_HEADER, TRUE);
  28. /**
  29. * Send the HTTPS GET request.
  30. */
  31. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  32. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  33. $response = curl_exec($curl);
  34. if ($response == FALSE) {
  35. print "curl_exec failed!\n";
  36. curl_close($curl);
  37. return ;
  38. }
  39. /**
  40. * Process the response returned by the server.
  41. */
  42. $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  43. $headers = substr($response, 0, $headerSize);
  44. $bodyContent = substr($response, $headerSize);
  45. curl_close($curl);
  46. if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
  47. file_put_contents($audioSaveFile, $bodyContent);
  48. print "The GET request succeed!\n";
  49. }
  50. else {
  51. print "The GET request failed: " . $bodyContent . "\n";
  52. }
  53. }
  54. function processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate) {
  55. $url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/v1/tts";
  56. /**
  57. * Set request parameters in JSON format in the HTTPS POST request body.
  58. */
  59. $taskArr = array(
  60. "appkey" => $appkey,
  61. "token" => $token,
  62. "text" => $text,
  63. "format" => $format,
  64. "sample_rate" => $sampleRate
  65. // voice Optional. The speaker. Default value: xiaoyun.
  66. // "voice" => "xiaoyun",
  67. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  68. // "volume" => 50,
  69. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  70. // "speech_rate" => 0,
  71. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  72. // "pitch_rate" => 0
  73. );
  74. $body = json_encode($taskArr);
  75. print "The POST request body content: " . $body . "\n";
  76. $curl = curl_init();
  77. curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  78. /**
  79. * Set the HTTPS POST URL.
  80. */
  81. curl_setopt($curl, CURLOPT_URL, $url);
  82. curl_setopt($curl, CURLOPT_POST, TRUE);
  83. /**
  84. * Set the HTTPS POST request header.
  85. * */
  86. $httpHeaders = array(
  87. "Content-Type: application/json"
  88. );
  89. curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
  90. /**
  91. * Set the HTTPS POST request body.
  92. */
  93. curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
  94. /**
  95. * Set the HTTPS header in the response.
  96. */
  97. curl_setopt($curl, CURLOPT_HEADER, TRUE);
  98. /**
  99. * Send the HTTPS POST request.
  100. */
  101. $response = curl_exec($curl);
  102. if ($response == FALSE) {
  103. print "curl_exec failed!\n";
  104. curl_close($curl);
  105. return ;
  106. }
  107. /**
  108. * Process the response returned by the server.
  109. */
  110. $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
  111. $headers = substr($response, 0, $headerSize);
  112. $bodyContent = substr($response, $headerSize);
  113. curl_close($curl);
  114. if (stripos($headers, "Content-Type: audio/mpeg") != FALSE || stripos($headers, "Content-Type:audio/mpeg") != FALSE) {
  115. file_put_contents($audioSaveFile, $bodyContent);
  116. print "The POST request succeed!\n";
  117. }
  118. else {
  119. print "The POST request failed: " . $bodyContent . "\n";
  120. }
  121. }
  122. $appkey = "Your appkey";
  123. $token = "Your token";
  124. $text = "Today is Monday. It is a fine day." ;
  125. $textUrlEncode = urlencode($text);
  126. $textUrlEncode = preg_replace('/\+/', '%20', $textUrlEncode);
  127. $textUrlEncode = preg_replace('/\*/', '%2A', $textUrlEncode);
  128. $textUrlEncode = preg_replace('/%7E/', '~', $textUrlEncode);
  129. $audioSaveFile = "syAudio.wav";
  130. $format = "wav";
  131. $sampleRate = 16000;
  132. processGETRequest($appkey, $token, $textUrlEncode, $audioSaveFile, $format, $sampleRate);
  133. // processPOSTRequest($appkey, $token, $text, $audioSaveFile, $format, $sampleRate);
  134. ?>

Node.js demo

Note: To install the request dependencies, run the following command in the directory of your demo file:

  1. npm install request --save

Sample code:

  1. const request = require('request');
  2. const fs = require('fs');
  3. function processGETRequest(appkey, token, text, audioSaveFile, format, sampleRate) {
  4. var url = 'https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts';
  5. /**
  6. * Set the URL request parameters.
  7. */
  8. url = url + '?appkey=' + appkey;
  9. url = url + '&token=' + token;
  10. url = url + '&text=' + text;
  11. url = url + '&format=' + format;
  12. url = url + '&sample_rate=' + sampleRate;
  13. // voice Optional. The speaker. Default value: xiaoyun.
  14. // url = url + "&voice=" + "xiaoyun";
  15. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  16. // url = url + "&volume=" + 50;
  17. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  18. // url = url + "&speech_rate=" + 0;
  19. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  20. // url = url + "&pitch_rate=" + 0;
  21. console.log(url);
  22. /**
  23. * Set the HTTPS GET request.
  24. * Set the encoding parameter to null, and set the HTTPS response body to the binary buffer type.
  25. */
  26. var options = {
  27. url: url,
  28. method: 'GET',
  29. encoding: null
  30. };
  31. request(options, function (error, response, body) {
  32. /**
  33. * Process the response returned by the server.
  34. */
  35. if (error != null) {
  36. console.log(error);
  37. }
  38. else {
  39. var contentType = response.headers['content-type'];
  40. if (contentType === undefined || contentType != 'audio/mpeg') {
  41. console.log(body.toString());
  42. console.log('The GET request failed!');
  43. }
  44. else {
  45. fs.writeFileSync(audioSaveFile, body);
  46. console.log('The GET request is succeed!');
  47. }
  48. }
  49. });
  50. }
  51. function processPOSTRequest(appkeyValue, tokenValue, textValue, audioSaveFile, formatValue, sampleRateValue) {
  52. var url = 'https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts';
  53. /**
  54. * Set request parameters in JSON format in the HTTPS POST request body.
  55. */
  56. var task = {
  57. appkey : appkeyValue,
  58. token : tokenValue,
  59. text : textValue,
  60. format : formatValue,
  61. sample_rate : sampleRateValue
  62. // voice Optional. The speaker. Default value: xiaoyun.
  63. // voice : 'xiaoyun',
  64. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  65. // volume : 50,
  66. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  67. // speech_rate : 0,
  68. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  69. // pitch_rate : 0
  70. };
  71. var bodyContent = JSON.stringify(task);
  72. console.log('The POST request body content: ' + bodyContent);
  73. /**
  74. * Set the HTTPS POST request header.
  75. */
  76. var httpHeaders = {
  77. 'Content-type' : 'application/json'
  78. }
  79. /**
  80. * Set the HTTPS POST request.
  81. * Set the encoding parameter to null, and set the HTTPS response body to the binary buffer type.
  82. */
  83. var options = {
  84. url: url,
  85. method: 'POST',
  86. headers: httpHeaders,
  87. body: bodyContent,
  88. encoding: null
  89. };
  90. request(options, function (error, response, body) {
  91. /**
  92. * Process the response returned by the server.
  93. */
  94. if (error != null) {
  95. console.log(error);
  96. }
  97. else {
  98. var contentType = response.headers['content-type'];
  99. if (contentType === undefined || contentType != 'audio/mpeg') {
  100. console.log(body.toString());
  101. console.log('The POST request failed!');
  102. }
  103. else {
  104. fs.writeFileSync(audioSaveFile, body);
  105. console.log('The POST request is succeed!');
  106. }
  107. }
  108. });
  109. }
  110. var appkey = 'Your appkey';
  111. var token = 'Your token';
  112. var text = 'Today is Monday. It is a fine day.' ;
  113. var textUrlEncode = encodeURIComponent(text)
  114. .replace(/[!'()*]/g, function(c) {
  115. return '%' + c.charCodeAt(0).toString(16);
  116. });
  117. console.log(textUrlEncode);
  118. var audioSaveFile = 'syAudio.wav';
  119. var format = 'wav';
  120. var sampleRate = 16000;
  121. processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate);
  122. // processPOSTRequest(appkey, token, text, audioSaveFile, format, sampleRate);

.Net demo

Note: The demo depends on System.Net.Http, System.Web, and Newtonsoft.Json.Linq.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Net.Http;
  7. using System.Web;
  8. using Newtonsoft.Json.Linq;
  9. namespace RESTfulAPI
  10. {
  11. class SpeechSynthesizerRESTfulDemo
  12. {
  13. private string appkey;
  14. private string token;
  15. public SpeechSynthesizerRESTfulDemo(string appkey, string token)
  16. {
  17. this.appkey = appkey;
  18. this.token = token;
  19. }
  20. public void processGETRequest(string text, string audioSaveFile, string format, int sampleRate)
  21. {
  22. /**
  23. * Set the HTTPS GET request.
  24. * 1. Use HTTPS.
  25. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  26. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  27. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  28. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  29. */
  30. string url = "http://nls-gateway.aliyuncs.com/stream/v1/tts";
  31. url = url + "?appkey=" + appkey;
  32. url = url + "&token=" + token;
  33. url = url + "&text=" + text;
  34. url = url + "&format=" + format;
  35. url = url + "&sample_rate=" + sampleRate.ToString();
  36. // voice Optional. The speaker. Default value: xiaoyun.
  37. // url = url + "&voice=" + "xiaoyun";
  38. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  39. // url = url + "&volume=" + 50;
  40. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  41. // url = url + "&speech_rate=" + 0;
  42. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  43. // url = url + "&pitch_rate=" + 0;
  44. System.Console.WriteLine(url);
  45. /**
  46. * Send the HTTPS GET request and process the response returned by the server.
  47. */
  48. HttpClient client = new HttpClient();
  49. HttpResponseMessage response = null;
  50. response = client.GetAsync(url).Result;
  51. string contentType = null;
  52. if (response.IsSuccessStatusCode)
  53. {
  54. string[] typesArray = response.Content.Headers.GetValues("Content-Type").ToArray();
  55. if (typesArray.Length > 0)
  56. {
  57. contentType = typesArray.First();
  58. }
  59. }
  60. if ("audio/mpeg".Equals(contentType))
  61. {
  62. byte[] audioBuff = response.Content.ReadAsByteArrayAsync().Result;
  63. FileStream fs = new FileStream(audioSaveFile, FileMode.Create);
  64. fs.Write(audioBuff, 0, audioBuff.Length);
  65. fs.Flush();
  66. fs.Close();
  67. System.Console.WriteLine("The GET request succeed!");
  68. }
  69. else
  70. {
  71. // The value of Content-Type is null or application/json.
  72. System.Console.WriteLine("Response status code and reason phrase: " +
  73. response.StatusCode + " " + response.ReasonPhrase);
  74. string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
  75. System.Console.WriteLine("The GET request failed: " + responseBodyAsText);
  76. }
  77. }
  78. public void processPOSTRequest(string text, string audioSaveFile, string format, int sampleRate)
  79. {
  80. /**
  81. * Set the HTTPS POST request.
  82. * 1. Use HTTPS.
  83. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  84. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  85. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  86. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  87. */
  88. string url = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts";
  89. JObject obj = new JObject();
  90. obj["appkey"] = appkey;
  91. obj["token"] = token;
  92. obj["text"] = text;
  93. obj["format"] = format;
  94. obj["sample_rate"] = sampleRate;
  95. // voice Optional. The speaker. Default value: xiaoyun.
  96. // obj["voice"] = "xiaoyun";
  97. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  98. // obj["volume"] = 50;
  99. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  100. // obj["speech_rate"] = 0;
  101. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  102. // obj["pitch_rate"] = 0;
  103. String bodyContent = obj.ToString();
  104. StringContent content = new StringContent(bodyContent, Encoding.UTF8, "application/json");
  105. /**
  106. * Send the HTTPS POST request and process the response returned by the server.
  107. */
  108. HttpClient client = new HttpClient();
  109. HttpResponseMessage response = client.PostAsync(url, content).Result;
  110. string contentType = null;
  111. if (response.IsSuccessStatusCode)
  112. {
  113. string[] typesArray = response.Content.Headers.GetValues("Content-Type").ToArray();
  114. if (typesArray.Length > 0)
  115. {
  116. contentType = typesArray.First();
  117. }
  118. }
  119. if ("audio/mpeg".Equals(contentType))
  120. {
  121. byte[] audioBuff = response.Content.ReadAsByteArrayAsync().Result;
  122. FileStream fs = new FileStream(audioSaveFile, FileMode.Create);
  123. fs.Write(audioBuff, 0, audioBuff.Length);
  124. fs.Flush();
  125. fs.Close();
  126. System.Console.WriteLine("The POST request succeed!");
  127. }
  128. else
  129. {
  130. System.Console.WriteLine("Response status code and reason phrase: " +
  131. response.StatusCode + " " + response.ReasonPhrase);
  132. string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
  133. System.Console.WriteLine("The POST request failed: " + responseBodyAsText);
  134. }
  135. }
  136. static void Main(string[] args)
  137. {
  138. if (args.Length < 2)
  139. {
  140. System.Console.WriteLine("SpeechSynthesizerRESTfulDemo need params: <token> <app-key>");
  141. return;
  142. }
  143. string token = args[0];
  144. string appkey = args[1];
  145. SpeechSynthesizerRESTfulDemo demo = new SpeechSynthesizerRESTfulDemo(appkey, token);
  146. string text = "Today is Monday. It is a fine day." ;
  147. // Encode the URL based on the RFC 3986 standard.
  148. string textUrlEncode = text;
  149. textUrlEncode = HttpUtility.UrlEncode(textUrlEncode, Encoding.UTF8)
  150. .Replace("+", "%20")
  151. .Replace("*", "%2A")
  152. .Replace("%7E", "~");
  153. System.Console.WriteLine(textUrlEncode);
  154. string audioSaveFile = "syAudio.wav";
  155. string format = "wav";
  156. int sampleRate = 16000;
  157. demo.processGETRequest(textUrlEncode, audioSaveFile, format, sampleRate);
  158. //demo.processPOSTRequest(text, audioSaveFile, format, sampleRate);
  159. }
  160. }
  161. }

GO demo

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. "net/http"
  6. "io/ioutil"
  7. "encoding/json"
  8. "strconv"
  9. "os"
  10. "bytes"
  11. "strings"
  12. )
  13. func processGETRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
  14. /**
  15. * Set the HTTPS GET request.
  16. * 1. Use HTTPS.
  17. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  18. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  19. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  20. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  21. */
  22. var url string = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts"
  23. url = url + "?appkey=" + appkey
  24. url = url + "&token=" + token
  25. url = url + "&text=" + text
  26. url = url + "&format=" + format
  27. url = url + "&sample_rate=" + strconv.Itoa(sampleRate)
  28. // voice Optional. The speaker. Default value: xiaoyun.
  29. // url = url + "&voice=" + "xiaoyun"
  30. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  31. // url = url + "&volume=" + strconv.Itoa(50)
  32. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  33. // url = url + "&speech_rate=" + strconv.Itoa(0)
  34. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  35. // url = url + "&pitch_rate=" + strconv.Itoa(0)
  36. fmt.Println(url)
  37. /**
  38. * Send the HTTPS GET request and process the response returned by the server.
  39. */
  40. response, err := http.Get(url)
  41. if err != nil {
  42. fmt.Println("The GET request failed!")
  43. panic(err)
  44. }
  45. defer response.Body.Close()
  46. contentType := response.Header.Get("Content-Type")
  47. body, _ := ioutil.ReadAll(response.Body)
  48. if ("audio/mpeg" == contentType) {
  49. file, _ := os.Create(audioSaveFile)
  50. defer file.Close()
  51. file.Write([]byte(body))
  52. fmt.Println("The GET request succeed!")
  53. } else {
  54. // The value of Content-Type is null or application/json.
  55. statusCode := response.StatusCode
  56. fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
  57. fmt.Println("The GET request failed: " + string(body))
  58. }
  59. }
  60. func processPOSTRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
  61. /**
  62. * Set the HTTPS POST request.
  63. * 1. Use HTTPS.
  64. * 2. Set the domain name for the speech synthesis service to nls-gateway-ap-southeast-1.aliyuncs.com.
  65. * 3. Set the request path of the speech synthesis API to /stream/v1/tts.
  66. * 4. Set the required request parameters: appkey, token, text, format, and sample_rate.
  67. * 5. Set the optional request parameters: voice, volume, speech_rate, and pitch_rate.
  68. */
  69. var url string = "https://nls-gateway-ap-southeast-1.aliyuncs.com/stream/v1/tts"
  70. bodyContent := make(map[string]interface{})
  71. bodyContent["appkey"] = appkey
  72. bodyContent["text"] = text
  73. bodyContent["token"] = token
  74. bodyContent["format"] = format
  75. bodyContent["sample_rate"] = sampleRate
  76. // voice Optional. The speaker. Default value: xiaoyun.
  77. // bodyContent["voice"] = "xiaoyun"
  78. // volume Optional. The volume. Value range: 0 to 100. Default value: 50.
  79. // bodyContent["volume"] = 50
  80. // speech_rate Optional. The speed. Value range: -500 to 500. Default value: 0.
  81. // bodyContent["speech_rate"] = 0
  82. // pitch_rate Optional. The intonation. Value range: -500 to 500. Default value: 0.
  83. // bodyContent["pitch_rate"] = 0
  84. bodyJson, err := json.Marshal(bodyContent)
  85. if err != nil {
  86. panic(nil)
  87. }
  88. fmt.Println(string(bodyJson))
  89. /**
  90. * Send the HTTPS POST request and process the response returned by the server.
  91. */
  92. response, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(bodyJson)))
  93. if err != nil {
  94. panic(err)
  95. }
  96. defer response.Body.Close()
  97. contentType := response.Header.Get("Content-Type")
  98. body, _ := ioutil.ReadAll(response.Body)
  99. if ("audio/mpeg" == contentType) {
  100. file, _ := os.Create(audioSaveFile)
  101. defer file.Close()
  102. file.Write([]byte(body))
  103. fmt.Println("The POST request succeed!")
  104. } else {
  105. // The value of Content-Type is null or application/json.
  106. statusCode := response.StatusCode
  107. fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
  108. fmt.Println("The POST request failed: " + string(body))
  109. }
  110. }
  111. func main() {
  112. var appkey string = "Your appkey"
  113. var token string = "Your token"
  114. var text string = "Today is Monday. It is a fine day."
  115. var textUrlEncode = text
  116. textUrlEncode = url.QueryEscape(textUrlEncode)
  117. textUrlEncode = strings.Replace(textUrlEncode, "+", "%20", -1)
  118. textUrlEncode = strings.Replace(textUrlEncode, "*", "%2A", -1)
  119. textUrlEncode = strings.Replace(textUrlEncode, "%7E", "~", -1)
  120. fmt.Println(textUrlEncode)
  121. var audioSaveFile string = "syAudio.wav"
  122. var format string = "wav"
  123. var sampleRate int = 16000
  124. processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate)
  125. // processPOSTRequest(appkey, token, text, audioSaveFile, format, sampleRate)
  126. }