一、调用第三方 TTS 服务
1. 使用 Google Text-to-Speech API
Google 提供了强大的 TTS 服务,支持高质量的语音合成和多种语言。
步骤:
1、注册 Google Cloud 并启用 TTS API :
- 在 Google Cloud Console 创建项目。
- 启用 "Text-to-Speech API"。
- 获取 API 密钥或服务账户凭据。
2、添加依赖 : 如果使用 Maven,添加以下依赖:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-texttospeech</artifactId>
<version>2.0.0</version>
</dependency>
3、代码实现 :
import com.google.cloud.texttospeech.v1.*;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class GoogleTTSExample {
public static void main(String[] args) throws Exception {
// 初始化客户端
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// 设置输入文本
SynthesisInput input = SynthesisInput.newBuilder().setText("Hello, this is a test of Google TTS.").build();
// 设置语音参数
VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
.setLanguageCode("en-US") // 语言代码
.setName("en-US-Standard-A") // 音色
.setSsmlGender(SsmlVoiceGender.FEMALE)
.build();
// 设置音频配置
AudioConfig audioConfig = AudioConfig.newBuilder()
.setAudioEncoding(AudioEncoding.MP3) // 输出格式
.build();
// 调用 TTS API
SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// 获取音频数据
byte[] audioContent = response.getAudioContent().toByteArray();
// 将音频保存为文件
try (OutputStream out = new FileOutputStream("output.mp3")) {
out.write(audioContent);
System.out.println("音频文件已生成:output.mp3");
}
}
}
}
2. 使用 Amazon Polly
Amazon Polly 是 AWS 提供的 TTS 服务,支持多种语言和音色。
步骤
1、注册 AWS 并启用 Polly 服务 :
- 在 AWS Console 创建账户。
- 启用 Polly 服务并获取访问密钥。
2、添加依赖 : 如果使用 Maven,添加以下依赖:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>polly</artifactId>
<version>2.20.0</version>
</dependency>
3、代码实现 :
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.PollyClient;
import software.amazon.awssdk.services.polly.model.*;
import java.io.FileOutputStream;
public class AmazonPollyExample {
public static void main(String[] args) {
// 初始化客户端
PollyClient polly = PollyClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
// 设置输入文本
SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder()
.text("Hello, this is a test of Amazon Polly.")
.voiceId(VoiceId.JOANNA) // 音色
.outputFormat(OutputFormat.MP3) // 输出格式
.build();
// 调用 TTS API
SynthesizeSpeechResponse response = polly.synthesizeSpeech(request);
// 获取音频数据
try (FileOutputStream outputStream = new FileOutputStream("output.mp3")) {
response.audioStream().transferTo(outputStream);
System.out.println("音频文件已生成:output.mp3");
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、使用开源 TTS 工具
1. 使用 FreeTTS
FreeTTS 是一个开源的 Java TTS 库,适合简单的语音合成需求。
步骤
1、下载 FreeTTS :
- 从 FreeTTS 官网 下载库文件。
2、代码实现 :
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTSExample {
public static void main(String[] args) {
// 初始化语音管理器
VoiceManager voiceManager = VoiceManager.getInstance();
Voice voice = voiceManager.getVoice("kevin16"); // 使用默认音色
if (voice != null) {
voice.allocate(); // 分配资源
voice.speak("Hello, this is a test of FreeTTS."); // 播放语音
voice.deallocate(); // 释放资源
} else {
System.out.println("无法加载语音引擎!");
}
}
}
2. 使用 MaryTTS
MaryTTS 是一个功能更强大的开源 TTS 系统,支持多语言和自定义音色。
步骤
1、安装 MaryTTS :
- 从 MaryTTS 官网 下载并运行服务器。
2、代码实现 :
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
public class MaryTTSExample {
public static void main(String[] args) throws Exception {
String text = "Hello, this is a test of MaryTTS.";
String url = "http://localhost:59125/process";
// 创建 HTTP 客户端
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 设置请求参数
String body = "INPUT_TEXT=" + text +
"&INPUT_TYPE=TEXT" +
"&OUTPUT_TYPE=AUDIO" +
"&AUDIO=WAVE" +
"&LOCALE=en_US" +
"&VOICE=dfki-prudence-hsmm";
post.setEntity(new StringEntity(body));
// 发送请求
try (CloseableHttpResponse response = httpClient.execute(post)) {
if (response.getStatusLine().getStatusCode() == 200) {
// 将音频保存为文件
try (FileOutputStream out = new FileOutputStream("output.wav")) {
response.getEntity().writeTo(out);
System.out.println("音频文件已生成:output.wav");
}
} else {
System.out.println("请求失败:" + EntityUtils.toString(response.getEntity()));
}
}
}
}
}
三、使用系统自带的语音功能
Java 可以通过调用操作系统自带的语音功能实现 TTS。例如,在 Windows 上可以使用 javax.speech
或 System
命令调用语音引擎。
示例代码(Windows 系统) :
public class SystemTTSExample {
public static void main(String[] args) {
String text = "Hello, this is a test of system TTS.";
try {
// 调用 Windows 的 PowerShell 命令
Runtime.getRuntime().exec("powershell -Command \"Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('" + text + "')\"");
System.out.println("语音播放完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、总结
在 Java 中实现 TTS 功能有多种选择:
- 第三方服务 (如 Google TTS、Amazon Polly):适合高质量、多语言的需求。
- 开源工具 (如 FreeTTS、MaryTTS):适合简单或自定义的需求。
- 系统自带功能 :适合快速原型开发。