https://ai.baidu.com/docs#/TTS-Online-Java-SDK/top
Java SDK Documentation
Introduction
Hello, and welcome to Baidu’s Text-to-Speech (TTS) service.
This documentation is intended for Java developers and outlines the technical details of Baidu’s TTS API service. If you have any questions regarding this documentation, please contact us via the following methods:
Submit a support ticket through the Baidu Cloud Console (select “Artificial Intelligence Services” as the inquiry category);
Quick communication via QQ groups: Look for the “Baidu Speech” group under the “QQ Support Groups” section at the bottom of the AI Open Platform homepage.
API Capabilities
API Name | Brief Description of API Capabilities
Text-to-Speech (TTS) | Technology that converts computer-generated or externally input text into intelligible, fluent spoken audio output.
Important Notes
Currently, the functionality of this SDK mirrors that of the REST API; it requires an internet connection to call the HTTP interface. The REST API supports the synthesis of up to 512 characters (1024 bytes) of text into MP3 format audio and offers no additional features. If you require features such as offline synthesis, please use the Android or iOS TTS SDKs.
Please ensure development strictly adheres to the parameters described in the documentation. Note the following points:
The length of the text to be synthesized must be less than 1024 bytes; if the text is longer, please use multiple requests. Do not exceed the text length limit.
There is no limit on the total number of calls to the TTS REST API, but the initial Queries Per Second (QPS) limit is 100. If the default quota does not meet your business needs, please apply for a quota increase via the console; we will process your request within two business days.
For mandatory fields, please fill in the information strictly according to the descriptions provided in the documentation. Version Update Log
Release Date Version Update Details
2018.1.26 4.1.1 Fixed issue where the server did not return Content-Type for speech synthesis; added logging
2017.12.12 3.4.1 Fixed speech synthesis issues
2017.11.10 3.3.1 Fixed issue where speech synthesis returned no ‘sn’ (serial number)
2017.10.18 3.2.1 Fixed proxy usage issues
2017.8.25 3.0.0 Updated SDK packaging method: integrated all AI services into a single SDK
2017.7.14 1.0.1 Updated SDK packaging method
2017.6.30 1.0.0 Added speech synthesis service interface
Quick Start
Installing the Speech Java SDK
Speech Java SDK Directory Structure
com.baidu.aip
├── auth // Signature-related classes
├── http // HTTP communication-related classes
├── client // Common classes
├── exception // Exception classes
├── speech
│ └── AipSpeech // AipSpeech class
└── util // Utility classes
Supported Java Version: 1.7+
View Source Code
The Java SDK source code is now publicly available; you can view the code, or modify and compile the SDK to suit your environment within the terms of the license. GitHub link: https://github.com/Baidu-AIP/java-sdk
Using Maven Dependency:
Simply add the following dependency. You can check the official Maven website for the version number.
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>${version}</version></dependency>
Steps to use the JAR package directly:
1. Download the Java SDK compressed package from the official website.
2. Extract the downloaded `aip-java-sdk-version.zip` and copy it into your project folder.
3. In Eclipse, right-click on the project and select “Properties -> Java Build Path -> Add JARs”. 4. Add the SDK package `aip-java-sdk-version.jar` and the third-party dependency packages `json-20160810.jar` and `log4j-1.2.17.jar` (where “version” represents the specific version number). Once added, you can use the Speech Java SDK in your project.
Create an AipSpeech instance
AipSpeech is the Java client for speech recognition; it provides a range of interaction methods for developers using the speech recognition service. Users can refer to the code below to create a new `AipSpeech` instance. It is recommended to use it as a singleton after initialization to avoid repeatedly fetching the `access_token`:
public class Sample { // Set APPID/AK/SK
public static final String APP_ID = “Your App ID”; public static final String API_KEY = “Your Api Key”; public static final String SECRET_KEY = “Your Secret Key”; public static void main(String[] args) { // Initialize an AipSpeech instance
AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY); // Optional: Set network connection parameters
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000); // Optional: Set proxy server address; choose either HTTP or socket proxy, or set neither
client.setHttpProxy(“proxy_host”, proxy_port); // Set HTTP proxy
client.setSocketProxy(“proxy_host”, proxy_port); // Set socket proxy
// Optional: Set log4j log output format; default configuration is used if not set
// This environment variable can also be set directly via JVM startup parameters
System.setProperty(“aip.log4j.conf”, “path/to/your/log4j.properties”); // Call the API
TtsResponse res = client.synthesis(“Hello Baidu”, “zh”, 1, null); byte[] data = res.getData();
JSONObject res1 = res.getResult(); if (data != null) { try {
Util.writeBytesToFileSystem(data, “output.mp3”);
} catch (IOException e) {
e.printStackTrace();
}
} if (res1 != null) {
System.out.println(res1.toString(2));
}
}
}
The content of the example `log4j.properties` file is as follows:
# Levels can be set: debug > info > error # debug: displays debug, info, error # info: displays info, error # error: displays only error log4j.rootLogger=debug,appender1 # log4j.rootLogger=info,appender1 # log4j.rootLogger=error,appender1 # Output to console log4j.appender.appender1=org.apache.log4j.ConsoleAppender # Layout style: PatternLayout log4j.appender.appender1.layout=org.apache.log4j.PatternLayout # Custom pattern # %r Time (0) # %t Method name (e.g., main) # %p Priority (DEBUG/INFO/ERROR) # %c Full name of the class (including package name) # %l Location of the event (class and line number) # %m Message specified in the code (e.g., the ‘message’ in log(message)) # %n Output a newline log4j.appender.appender1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss:SSS}][%t][%p] -%l %m%n
In the code above, the `APP_ID` constant is created in the Baidu Cloud console. The `API_KEY` and `SECRET_KEY` constants are assigned to the user by the system after the application is created; both are strings used to identify the user and perform signature verification for access, and they can be viewed in the application list within the AI service console.
Configuring AipSpeech
If users need to configure specific parameters for AipSpeech, they can call the corresponding methods after instantiating the AipSpeech object. Currently, only the following parameters are supported:
Method Description
setConnectionTimeoutInMillis Timeout for establishing a connection (unit: milliseconds)
setSocketTimeoutInMillis Timeout for data transmission over an open connection (unit: milliseconds)
setHttpProxy Set HTTP proxy server
setSocketProxy Set socket proxy server (choose either HTTP or socket proxy type, not both)
Method Description
Speech Synthesis
Method Description
Developers can easily access speech synthesis capabilities using this method.
Request Description
The length of the text to be synthesized must be less than 1024 bytes; if the text is longer, multiple requests can be used. The text length cannot exceed the limit.
For example, to synthesize a text into an audio file:
public void synthesis(AipSpeech client)
{
TtsResponse res = client.synthesis(“你好百度”, “zh”, 1, null);
System.out.println(res.getErrorCode()); // Set optional parameters
HashMap<String, Object> options = new HashMap<String, Object>();
options.put(“spd”, “5”);
options.put(“pit”, “5”);
options.put(“per”, “4”);
TtsResponse res = client.synthesis(“你好百度”, “zh”, 1, options);
System.out.println(res.getErrorCode()); JSONObject result = res.getResult(); // The content returned by the server, null if the synthesis is successful, and includes error_no and other information if it fails
byte[] data = res.getData(); // The generated audio data}
Parameters Type Description Required
tex String The synthesized text is encoded in UTF-8.
Please note that the text length must be less than 1024 bytes.
cuid String: User unique identifier used to distinguish users.
Enter the machine’s MAC address or IMEI code, with a length of no more than 60 characters.
spd String Speech rate; values 0–9; default is 5 (medium speed). No
pit String Pitch; values 0–9; default is 5 (medium pitch). No
vol String Volume; values 0–15; default is 5 (medium volume). No
per String Speaker selection: 0 for female, 1 for male,
3 for emotional synthesis (Du Xiaoyao), 4 for emotional synthesis (Du Yaya); default is standard female. No
Response example:
Returns a `TtsResponse` object. If synthesis is successful, the downstream data is a binary audio file contained within the `data` field. If an error occurs during synthesis, the return value is populated in the `result` field.
Failure response:
// Failure response: { “err_no”:500, “err_msg”:”notsupport.”, “sn”:”abcdefgh”, “idx”:1}
Error information
Error response format
If the request fails, the JSON text returned by the server includes the following parameters:
error_code: Error code.
error_msg: Error description to help understand and resolve the error.
Error codes
Error codes returned by SDK local parameter checks:
error_code error_msg Remarks
SDK108 connection or read data time out Connection or data read timeout
Error codes returned by the server
Error code Meaning
500 Unsupported input
501 Incorrect input parameters
502 Token verification failed
503 Synthesis backend error