The long-text speech synthesis RESTful API supports HTTPS POST requests. You can upload the text that you want to synthesize to the server using an HTTPS POST request. The server then returns the speech synthesis result.
Features
The API supports the following settings:
Audio format for synthesis: .pcm, .wav, and .mp3.
Audio sample rate for synthesis: 8000 Hz and 16000 Hz.
Multiple voices.
Adjustable speech rate, pitch, and volume.
Data retrieval methods: polling or callbacks.
Use the streaming synthesis mechanism: As the quality of text-to-speech (TTS) synthesis improves, the complexity of the algorithm increases, which can lead to longer synthesis times. Streaming synthesis provides faster response times. This document and the software development kit (SDK) examples contain sample code for stream processing.
Direct calls to the RESTful API from pure JavaScript are not supported: Directly accessing the RESTful API using pure JavaScript can cause cross-domain issues (Cross-Origin Resource Sharing, CORS) and may expose your AppKey.
Prerequisites
Obtain a project AppKey. For more information, see Create a project.
Obtain an access token. For more information, see Overview of how to obtain a token.
Endpoints
Access Type | Description | URL | Host |
Public access | All servers can use the public access URL. | https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async | nls-gateway-cn-shanghai.aliyuncs.com |
Internal network access | Use the internal network access URL if you are using an ECS instance in the China (Shanghai) region. | http://nls-gateway-cn-shanghai-internal.aliyuncs.com/rest/v1/tts/async | nls-gateway-cn-shanghai-internal.aliyuncs.com |
Supported protocols:
Public access: Supports HTTP and HTTPS.
ECS internal network access: Supports only HTTP.
The examples in this topic use public access. You can adapt the URL as needed for your business scenario.
Upload text using the POST method
A complete speech synthesis RESTful API POST request includes the following elements:
URL
Protocol
URL
Method
HTTPS
https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async
POST
HTTPS POST request body
The request body is a JSON-formatted string that consists of request parameters. Therefore, the
Content-Typein the POST request header must be set to `application/json`. The following is an example.{ "payload":{ "tts_request":{ "voice":"xiaoyun", "sample_rate":16000, "format":"wav", "text":"The weather is nice and sunny today", "enable_subtitle": true }, "enable_notify":false }, "context":{ "device_id":"my_device_id" }, "header":{ "appkey":"yourAppkey", "token":"yourToken" } }
Request and response
After you send a request, the server returns a response message to the client in the HTTP body, regardless of whether the call succeeds or fails. The response format for HTTPS GET and HTTPS POST requests is the same. The result is included in the HTTPS body. The success or failure of the response is indicated by the Content-Type field in the HTTPS header:
Successful response
The body is a JSON-formatted string. A
statusfield value of 200 indicates that the request was successful.The
datafield in the body contains the task_id.
Failed response
The HTTPS header does not have a
Content-Typefield, or theContent-Typefield isapplication/json. This indicates that the synthesis has failed. The error message is in the body.The
X-NLS-RequestIdfield in the HTTPS header contains thetask_idof the request task.The body contains the error message as a JSON-formatted string.
The error message fields are described in the following table.
Name
Type
Description
task_id
String
The 32-bit request task ID. Record this value for troubleshooting.
error_code
Integer
The service status code.
error_message
String
The service status description.
Successful response after sending a request
{ "status":200, "error_code":20000000, "error_message":"SUCCESS", "request_id":"f0a9e2c49e9049e78730a3bf0b32****", "data":{ "task_id":"35d9f813e00b11e9a2ce9ba0d6a2****" } }Failed response after sending a request
{ "error_message":"Meta:ACCESS_DENIED:The token 'fdf' is invalid!", "error_code":40000001, "request_id":"0d8c0eea55824aada9a374aec650****", "url":"/rest/v1/tts/async", "status":400 }
Retrieve the synthesis result
Based on the `task_id` that is returned in the successful response from the previous step, you can send a GET request or use polling to retrieve and download the synthesized file.
Parameter | Example |
URL | https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async |
appkey | Your AppKey. |
token | Your token. |
task_id | The task_id returned in the successful response from the previous step. |
The following example shows a GET request to retrieve the synthesis result:
https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async?appkey={Appkey}&task_id={task_id}&token={Token}The following sample shows a successful response for a command execution or for polling the server-side synthesis status. The audio_address is the download link for the synthesized speech.
The HTTP download address corresponding to the audio_address field is valid for a maximum of 7 days.
/// Intermediate status returned by the server during polling.
{
"status":200,
"error_code":20000000,
"error_message":"RUNNING",
"request_id":"a3370c49a29148e78b39978f98ba****",
"data":{
"task_id":"35d9f813e00b11e9a2ce9ba0d6a2****",
"audio_address":null,
"notify_custom":null
}
}
/// The final synthesis result is obtained.
{
"status":200,
"error_code":20000000,
"error_message":"SUCCESS",
"request_id":"c541eae489af48d69dae2d2e203a****",
"data":{
"sentences":[
{
"text":"Long-text speech synthesis interface",
"begin_time":"0",
"end_time":"2239"
},
{
"text":"Return all audio corresponding to the text at once. Now need to add sentence-level timestamp information",
"begin_time":"2239",
"end_time":"8499"
},
{
"text":"Customers can use this information to implement playback control functions",
"begin_time":"8499",
"end_time":"12058"
}
],
"task_id":"f4e9bf53cb1611eab327b15f61b4****",
"audio_address":"This is the generated URL address",
"notify_custom":""
}
}If `enable_notify` and `notify_url` are enabled, the callback result is as follows:
{
"data": {
"audio_address": "http://nls-cloud-cn-shanghai.oss-cn-shanghai.aliyuncs.com/******.wav",
"task_id": "e3a06366d**************e1257693b"
},
"request_id": "edc6b5ab4***********223c8ace71",
"status": 20000000,
"error_code": 20000000,
"error_message": "SUCCESS"
} Service status codes
Status code | Service status | Solution |
20000000 | The request is successful. | None. |
40000000 | Default client error code. | Check the corresponding error message. |
40000001 | Identity authentication failed. | Check whether the token is correct and whether it has expired. |
40000002 | Invalid message. | Check whether the sent message meets the requirements. |
40000003 | Invalid parameter. | Check whether the parameter values are valid. |
40000004 | Idle timeout. | Confirm that data has not been sent to the server for an extended period. |
40000005 | Too many requests. | Check if the number of concurrent connections or requests per second has been exceeded. |
40000010 | The trial period has ended, and the commercial version is not activated, or your account has an overdue payment. | Log on to the console to check the service activation status and your account balance. |
50000000 | Default server-side error. | An internal service error occurred. The client must retry the request. |
50000001 | Internal gRPC call error. | An internal service error occurred. The client must retry the request. |
Java example
For more Java examples, download nls-restful-java-demo.
The dependency file content is as follows:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>The sample code is as follows:
package com.alibaba.nls.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This example demonstrates how to use long-text speech synthesis.
*/
public class SpeechLongSynthesizerRestfulDemo {
private static Logger logger = LoggerFactory.getLogger(SpeechLongSynthesizerRestfulDemo.class);
private String accessToken;
private String appkey;
public SpeechLongSynthesizerRestfulDemo(String appkey, String token) {
this.appkey = appkey;
this.accessToken = token;
}
public void processPOSTRequest(String text, String format, int sampleRate, String voice) {
String url = "https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async";
// Concatenate the content of the HTTP POST request body.
JSONObject context = new JSONObject();
// Set device_id. You can set it to a custom string or a device information ID.
context.put("device_id", "my_device_id");
JSONObject header = new JSONObject();
// Set your AppKey. To obtain an AppKey, go to the console: https://nls-portal.console.aliyun.com/applist
header.put("appkey", appkey);
// Set your token. For more information about how to obtain a token, see: https://help.aliyun.com/document_detail/450514.html
header.put("token", accessToken);
// voice: The voice. This parameter is optional. Default value: xiaoyun.
// volume: The volume. The value ranges from 0 to 100. This parameter is optional. Default value: 50.
// speech_rate: The speech rate. The value ranges from -500 to 500. This parameter is optional. Default value: 0.
// pitch_rate: The pitch. The value ranges from -500 to 500. This parameter is optional. Default value: 0.
JSONObject tts = new JSONObject();
tts.put("text", text);
// Set the voice.
tts.put("voice", voice);
// Set the encoding format.
tts.put("format", format);
// Set the sample rate.
tts.put("sample_rate", sampleRate);
// Set the volume. Optional.
//tts.put("volume", 100);
// Set the speech rate. Optional.
//tts.put("speech_rate", 200);
// The long-text TTS RESTful API supports sentence-level timestamps. The default value is false.
tts.put("enable_subtitle", true);
JSONObject payload = new JSONObject();
// Optional. Specifies whether to set a callback. If you set this parameter, the server calls back the webhook address that you set after long-text speech synthesis is complete and pushes the request status to the client.
payload.put("enable_notify", false);
payload.put("notify_url", "http://123.com");
payload.put("tts_request", tts);
JSONObject json = new JSONObject();
json.put("context", context);
json.put("header", header);
json.put("payload", payload);
String bodyContent = json.toJSONString();
logger.info("POST Body Content: " + bodyContent);
// Send the request.
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");
System.out.println("contentType = " + contentType);
// Obtain the result and perform further processing based on the response.
String result = response.body().string();
response.close();
System.out.println("result = " + result);
JSONObject resultJson = JSON.parseObject(result);
if(resultJson.containsKey("error_code") && resultJson.getIntValue("error_code") == 20000000) {
logger.info("Request Success! task_id = " + resultJson.getJSONObject("data").getString("task_id"));
String task_id = resultJson.getJSONObject("data").getString("task_id");
String request_id = resultJson.getString("request_id");
/// Optional: Poll the synthesis status on the server. This polling operation is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
waitLoop4Complete(url, appkey, accessToken, task_id, request_id);
}else {
logger.error("Request Error: status=" + resultJson.getIntValue("status")
+ ", error_code=" + resultJson.getIntValue("error_code")
+ ", error_message=" + resultJson.getString("error_message"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/// Poll the synthesis status of a request on the server based on specific information. This polling operation is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
private void waitLoop4Complete(String url, String appkey, String token, String task_id, String request_id) {
String fullUrl = url + "?appkey=" + appkey + "&task_id=" + task_id + "&token=" + token + "&request_id=" + request_id;
System.out.println("query url = " + fullUrl);
while(true) {
Request request = new Request.Builder().url(fullUrl).get().build();
try {
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String result = response.body().string();
response.close();
System.out.println("waitLoop4Complete = " + result);
JSONObject resultJson = JSON.parseObject(result);
if(resultJson.containsKey("error_code")
&& resultJson.getIntValue("error_code") == 20000000
&& resultJson.containsKey("data")
&& resultJson.getJSONObject("data").getString("audio_address") != null) {
logger.info("Tts Finished! task_id = " + resultJson.getJSONObject("data").getString("task_id"));
logger.info("Tts Finished! audio_address = " + resultJson.getJSONObject("data").getString("audio_address"));
break;
}else {
logger.info("Tts Queuing...");
}
// Poll the status every 10 seconds.
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("SpeechLongSynthesizerRestfulDemo need params: <token> <app-key>");
System.exit(-1);
}
String token = args[0];
String appkey = args[1];
SpeechLongSynthesizerRestfulDemo demo = new SpeechLongSynthesizerRestfulDemo(appkey, token);
String text = "Behind my house is a large garden, which is said to be called the Hundred-Grass Garden. It has long since been sold, along with the house, to the descendants of Zhu Wen Gong. It has been seven or eight years since I last saw it. It seems there are only some wild grasses there now, but back then, it was my paradise.";
String format = "wav";
int sampleRate = 16000;
String voice = "siyue";
demo.processPOSTRequest(text, format, sampleRate, voice);
}
}Python example
For Python 2, use the `httplib` module. For Python 3, use the `http.client` module.
When you create an HTTP or HTTPS connection, use the `httplib` module for Python 2 and the `http.client` module for Python 3:
Python 2.x
Create an HTTP connection
import httplib host = 'nls-gateway-cn-shanghai.aliyuncs.com' conn = httplib.HTTPConnection(host)Create an HTTPS connection
import httplib host = 'nls-gateway-cn-shanghai.aliyuncs.com' conn = httplib.HTTPSConnection(host)Python 3.x
Create an HTTP connection
import http.client host = 'nls-gateway-cn-shanghai.aliyuncs.com' conn = http.client.HTTPConnection(host)Create an HTTPS connection
import http.client host = 'nls-gateway-cn-shanghai.aliyuncs.com' conn = http.client.HTTPSConnection(host)Use the RFC 3986 specification for URL encoding. For Python 2, use `urllib.quote` from the `urllib` module. For Python 3, use `urllib.parse.quote_plus` from the `urllib.parse` module.
Python 3.x
Python 2.x
PHP example
The PHP example uses cURL functions. This requires PHP 4.0.2 or later and the cURL extension to be installed.
<?php
// Poll the synthesis status of a request on the server based on specific information every 10 seconds. This polling operation is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
function waitLoop4Complete($url, $appkey, $token, $task_id, $request_id) {
$fullUrl = $url . "?appkey=" . $appkey . "&task_id=" . $task_id . "&token=" . $token . "&request_id=" . $request_id;
print "query url = " . $fullUrl . "\n";
while(true) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, $fullUrl);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
$response = curl_exec($curl);
if ($response == FALSE) {
print "curl_exec failed!\n";
curl_close($curl);
return ;
}
// Process the response from the server.
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$bodyContent = substr($response, $headerSize);
print $bodyContent."\n";
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($http_code != 200) { // If the request fails, check whether the call is correct.
print "tts request failure, error code = " . $http_code . "\n";
curl_close($curl);
return ;
}
curl_close($curl);
$data = json_decode($bodyContent, true);
// If $data["data"]["audio_address"] == null, it indicates that the synthesis is not yet complete. You need to wait.
if(isset($data["error_code"]) && $data["error_code"] == 20000000
&& isset($data["data"]) && $data["data"]["audio_address"]== null){
print "Tts Queuing...please wait..." . "\n";
}
else if(isset($data["error_code"]) && $data["error_code"] == 20000000
&& isset($data["data"]) && $data["data"]["audio_address"] != "") {
print "Tts Finished! task_id = " . $data["data"]["task_id"] . "\n";
print "Tts Finished! audio_address = " . $data["data"]["audio_address"] . "\n";
break;
}
// Poll the status every 10 seconds.
sleep(10);
}
}
// The long-text speech synthesis RESTful API supports POST calls but not GET requests. After sending a request, you can poll the status or wait for the server to automatically call back after synthesis (if callback parameters are set).
function requestLongTts4Post($appkey, $token, $text, $voice, $format, $sampleRate) {
$url = "https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async";
// Concatenate the content of the HTTP POST request body.
$header = array("appkey" => $appkey, "token" => $token);
$context = array("device_id" => "my_device_id");
$tts_request = array("text" => $text, "format" => $format, "voice" => $voice, "sample_rate" => $sampleRate, "enable_subtitle" => false);
$payload = array("enable_notify" => true, "notify_url" => "http://123.com", "tts_request" => $tts_request);
$tts_body = array("context" => $context, "header" => $header, "payload" => $payload);
$body = json_encode($tts_body);
print "The POST request body content: " . $body . "\n";
$httpHeaders = array("Content-Type: application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
$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);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($http_code != 200) {
print "tts request failure, error code = " . $http_code . "\n";
print "tts request failure, response = " . $bodyContent . "\n";
return ;
}
curl_close($curl);
print $bodyContent . "\n";
$data = json_decode($bodyContent, true);
if( isset($data["error_code"]) && $data["error_code"] == 20000000) {
$task_id = $data["data"]["task_id"];
$request_id = $data["request_id"];
print "Request Success! task_id = " . $task_id . "\n";
print "Request Success! request_id = " . $request_id . "\n";
/// Note: Polling the synthesis status on the server is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
waitLoop4Complete($url, $appkey, $token, $task_id, $request_id);
} else {
print "Request Error: status=" . $data["status"] . "; error_code=" . $data["error_code"] . "; error_message=" . $data["error_message"] . "\n";
}
}
$appkey = "yourAppkey";
$token = "yourToken";
$text = "Today is Monday, and the weather is quite nice.";
$format = "wav";
$voice = "xiaogang";
$sampleRate = 16000;
requestLongTts4Post($appkey, $token, $text, $voice, $format, $sampleRate);
?>Node.js example
First, install the request dependency. Run the following command in the directory where your sample file is located:
npm install request --saveThe sample code is as follows:
const request = require('request');
const fs = require('fs');
// The long-text speech synthesis RESTful API supports POST calls but not GET requests. After sending a request, you can poll the status or wait for the server to automatically call back after synthesis (if callback parameters are set).
function requestLongTts4Post(textValue, appkeyValue, tokenValue, voiceValue, formatValue, sampleRateValue) {
var url = "https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async"
console.log(url);
// The request parameters. Enter them as a JSON-formatted string in the body of the HTTPS POST request.
var context = {
device_id : "device_id",
};
var header = {
appkey : appkeyValue,
token : tokenValue,
};
var tts_request = {
text : textValue,
voice : voiceValue,
format : formatValue,
"sample_rate" : sampleRateValue,
"enable_subtitle" : false
};
var payload = {
"enable_notify" : false,
"notify_url": "http://123.com",
"tts_request" : tts_request,
};
var tts_body = {
"context" : context,
"header" : header,
"payload" : payload
};
var bodyContent = JSON.stringify(tts_body);
console.log('The POST request body content: ' + bodyContent);
// Set the HTTPS POST request header.
var httpHeaders = {'Content-type' : 'application/json'};
// Set the HTTPS POST request.
// The encoding must be set to null. The body of the HTTPS response is a binary Buffer.
var options = {
url: url,
method: 'POST',
headers: httpHeaders,
body: bodyContent,
encoding: null
};
request(options, function (error, response, body) {
// Process the response from the server.
if (error != null) {
console.log(error);
} else {
if(response.statusCode != 200) {
console.log("Http Request Fail: " + response.statusCode + "; " + body.toString());
return;
}
console.log("response result: " + body.toString());
var code = 0;
var task_id = "";
var request_id = "";
var json = JSON.parse(body.toString());
console.info(json);
for(var key in json){
if(key=='error_code'){
code = json[key]
} else if(key=='request_id'){
request_id = json[key]
} else if(key == "data") {
task_id = json[key]["task_id"];
}
}
if(code == 20000000) {
console.info("Request Success! task_id = " + task_id);
console.info("Request Success! request_id = " + request_id);
/// Note: Polling the synthesis status on the server is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
waitLoop4Complete(url, appkey, token, task_id, request_id);
} else {
console.info("Request Error: status=" + $data["status"] + "; error_code=" + $data["error_code"] + "; error_message=" + $data["error_message"]);
}
}
});
}
// Poll the synthesis status of a request on the server based on specific information every 10 seconds. This polling operation is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
function waitLoop4Complete(urlValue, appkeyValue, tokenValue, task_id_value, request_id_value) {
var fullUrl = urlValue + "?appkey=" + appkeyValue + "&task_id=" + task_id_value + "&token=" + tokenValue + "&request_id=" + request_id_value;
console.info("query url = " + fullUrl);
//while(true) {
var timer = setInterval(() => {
var options = {
url: fullUrl,
method: 'GET'
};
console.info("query url = " + fullUrl);
request(options, function (error, response, body) {
// Process the response from the server.
if (error != null) {
console.log(error);
} else if(response.statusCode != 200) {
console.log("Http Request Fail: " + response.statusCode + "; " + body.toString());
return;
} else {
console.log("query result: " + body.toString());
var code = 0;
var task_id = "";
var output_url = "";
var json = JSON.parse(body.toString());
console.info(json);
for(var key in json){
if(key=='error_code'){
code = json[key]
} else if(key=='request_id'){
request_id = json[key]
} else if(key == "data" && json["data"] != null) {
task_id = json[key]["task_id"];
audio_address = json[key]["audio_address"];
}
}
if(code == 20000000 && audio_address == null) {
console.info("Tts Queuing...please wait...");
}
else if(code == 20000000 && audio_address != "") {
console.info("Tts Finished! task_id = " + task_id);
console.info("Tts Finished! audio_address = " + audio_address);
// Exit polling.
clearInterval(timer);
}
}
}
);
}
, 10000);
}
var appkey = 'yourAppkey';
var token = 'yourToken';
var text = 'Today is Monday, and the weather is quite nice.';
var voice = "xiaogang";
var format = 'wav';
var sampleRate = 16000;
requestLongTts4Post(text, appkey, token, voice, format, sampleRate);Go example
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
// The long-text speech synthesis RESTful API supports POST calls but not GET requests. After sending a request, you can poll the status or wait for the server to automatically call back after synthesis (if callback parameters are set).
func requestLongTts4Post(text string, appkey string, token string) {
var url string = "https://nls-gateway-cn-shanghai.aliyuncs.com/rest/v1/tts/async"
// Concatenate the content of the HTTP POST request body.
context := make(map[string]interface{})
context["device_id"] = "test-device"
header := make(map[string]interface{})
header["appkey"] = appkey
header["token"] = token
tts_request := make(map[string]interface{})
tts_request["text"] = text
tts_request["format"] = "wav"
tts_request["voice"] = "xiaogang"
tts_request["sample_rate"] = 16000
tts_request["enable_subtitle"] = false
payload := make(map[string]interface{})
payload["enable_notify"] = false
payload["notify_url"] = "http://123.com"
payload["tts_request"] = tts_request
ttsBody := make(map[string]interface{})
ttsBody["context"] = context
ttsBody["header"] = header
ttsBody["payload"] = payload
ttsBodyJson, err := json.Marshal(ttsBody)
if err != nil {
panic(nil)
}
fmt.Println(string(ttsBodyJson))
// Send an HTTPS POST request and process the response from the server.
response, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(ttsBodyJson)))
if err != nil {
panic(err)
}
defer response.Body.Close()
contentType := response.Header.Get("Content-Type")
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(contentType))
fmt.Println(string(body))
statusCode := response.StatusCode
if statusCode == 200 {
fmt.Println("The POST request succeed!")
var f interface{}
err := json.Unmarshal(body, &f)
if err != nil {
fmt.Println(err)
}
// Parse the task_id (important) and request_id from the message body.
var taskId string = ""
var requestId string = ""
m := f.(map[string]interface{})
for k, v := range m {
if k == "error_code" {
fmt.Println("error_code = ", v)
} else if k == "request_id" {
fmt.Println("request_id = ", v)
requestId = v.(string)
} else if k == "data" {
fmt.Println("data = ", v)
data := v.(map[string]interface{})
fmt.Println(data)
taskId = data["task_id"].(string)
}
}
// Note: Polling the synthesis status on the server is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
waitLoop4Complete(url, appkey, token, taskId, requestId)
} else {
fmt.Println("The POST request failed: " + string(body))
fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
}
}
// Poll the synthesis status of a request on the server based on specific information every 10 seconds. This polling operation is not required. If a webhook URL is set, the server actively calls back after the synthesis is complete.
func waitLoop4Complete(url string, appkey string, token string, task_id string, request_id string) {
var fullUrl string = url + "?appkey=" + appkey + "&task_id=" + task_id + "&token=" + token + "&request_id=" + request_id
fmt.Println("fullUrl=" + fullUrl)
for {
response, err := http.Get(fullUrl)
if err != nil {
fmt.Println("The GET request failed!")
panic(err)
}
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println("waitLoop4Complete = ", string(body))
var f interface{}
json.Unmarshal(body, &f)
if err != nil {
fmt.Println(err)
}
// Parse the task_id (important) and request_id from the message body.
var code float64 = 0
var taskId string = ""
var audioAddress string = ""
m := f.(map[string]interface{})
for k, v := range m {
if k == "error_code" {
code = v.(float64)
} else if k == "request_id" {
} else if k == "data" {
if v != nil {
data := v.(map[string]interface{})
taskId = data["task_id"].(string)
if data["audio_address"] == nil {
fmt.Println("Tts Queuing...,please wait...")
} else {
audioAddress = data["audio_address"].(string)
}
}
}
}
if code == 20000000 && audioAddress != "" {
fmt.Println("Tts Finished! task_id = " + taskId)
fmt.Println("Tts Finished! audio_address = " + audioAddress)
break
} else {
// Poll the status every 10 seconds.
time.Sleep(time.Duration(10) * time.Second)
}
}
}
func main() {
var appkey string = "yourAppkey"
var token string = "yourToken"
var text string = "Today is Monday, and the weather is quite nice."
requestLongTts4Post(text, appkey, token)
}