本文目录导读:

- 方案一:使用Java原生库(离线、免费、中文支持好)
- 方案二:调用云端API(在线、音质好、支持多种语言)
- 方案三:使用操作系统TTS(Windows/Mac/Linux)
- 方案四:调用WebSocket协议(低延迟、实时性强)
- 推荐选择
将TTS(文本转语音)集成到Java应用中,主要有以下几种主流方案,具体选择取决于你的应用场景(在线/离线、成本、语言、音质要求):
使用Java原生库(离线、免费、中文支持好)
FreeTTS(适合英文,中文支持较差)
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTSExample {
public static void main(String[] args) {
System.setProperty("freetts.voices",
"com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
VoiceManager voiceManager = VoiceManager.getInstance();
Voice voice = voiceManager.getVoice("kevin16");
if (voice != null) {
voice.allocate();
voice.speak("Hello, this is FreeTTS speaking!");
voice.deallocate();
}
}
}
缺点:中文支持差,声音机械感强,已停止维护。
MaryTTS(支持多语言,包括中文)
// Maven依赖
<dependency>
<groupId>de.dfki.mary</groupId>
<artifactId>marytts</artifactId>
<version>5.2</version>
</dependency>
// 代码示例
import marytts.LocalMaryInterface;
import marytts.MaryInterface;
import marytts.util.data.audio.AudioPlayer;
import javax.sound.sampled.AudioInputStream;
public class MaryTTSExample {
public static void main(String[] args) throws Exception {
MaryInterface marytts = new LocalMaryInterface();
marytts.setVoice("cmu-slt-hsmm"); // 英文女声
// 中文可用:dfki-pavoque-styles
AudioInputStream audio = marytts.generateAudio("你好,世界!");
AudioPlayer player = new AudioPlayer();
player.setAudio(audio);
player.start();
}
}
优点:支持多种语言,可定制发音。
VOICEVOX(日语,但部分库可扩展)
适用于专门日语场景,如使用 voicevox4j 调用本地VOICEVOX引擎。
调用云端API(在线、音质好、支持多种语言)
百度语音合成(推荐中文场景)
// Maven依赖
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.19</version>
</dependency>
// 代码示例
import com.baidu.aip.speech.AipSpeech;
import org.json.JSONObject;
public class BaiduTTSExample {
public static final String APP_ID = "你的APP_ID";
public static final String API_KEY = "你的API_KEY";
public static final String SECRET_KEY = "你的SECRET_KEY";
public static void main(String[] args) {
AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
// 文本转语音
JSONObject res = client.synthesis("你好,百度语音合成", "zh", 1, null);
byte[] data = res.getJSONObject("result").getString("data").getBytes();
// 保存为mp3文件或直接播放
// saveToFile(data, "output.mp3");
}
}
阿里云语音合成
// Maven依赖
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-tts</artifactId>
<version>2.2.0</version>
</dependency>
// 代码示例
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.NlsClient;
import com.alibaba.nls.client.SpeechSynthesizer;
import com.alibaba.nls.client.SpeechSynthesizerCallback;
public class AliyunTTSExample {
public static void main(String[] args) {
NlsClient client = new NlsClient("your-access-key-id", "your-access-key-secret");
SpeechSynthesizer synthesizer = client.createSynthesizer();
synthesizer.setVoice("xiaoyun"); // 中文女声
synthesizer.setText("你好,世界");
synthesizer.start();
// 处理音频流...
}
}
Google Cloud Text-to-Speech
// Maven依赖
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-texttospeech</artifactId>
<version>2.3.0</version>
</dependency>
// 代码示例
import com.google.cloud.texttospeech.v1.*;
import com.google.protobuf.ByteString;
public class GoogleTTSExample {
public static void main(String[] args) throws Exception {
try (TextToSpeechClient client = TextToSpeechClient.create()) {
SynthesisInput input = SynthesisInput.newBuilder()
.setText("Hello, World!")
.build();
VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
.setLanguageCode("en-US")
.setSsmlGender(SsmlVoiceGender.NEUTRAL)
.build();
AudioConfig config = AudioConfig.newBuilder()
.setAudioEncoding(AudioEncoding.MP3)
.build();
SynthesizeSpeechResponse response = client.synthesizeSpeech(input, voice, config);
ByteString audioContents = response.getAudioContent();
// 写入文件或播放
}
}
}
使用操作系统TTS(Windows/Mac/Linux)
Java Speech API (JSAPI) + 原生TTS引擎
import javax.speech.*;
import javax.speech.synthesis.*;
import java.util.Locale;
public class NativeTTSExample {
public static void main(String[] args) throws Exception {
// 初始化语音合成器
Synthesizer synth = Central.createSynthesizer(null);
synth.allocate();
synth.resume();
// 设置中文语音
Voice voice = new Voice();
voice.setLocale(Locale.CHINESE);
synth.getSynthesizerProperties().setVoice(voice);
// 朗读文本
synth.speakPlainText("你好,世界!", null);
synth.waitEngineState(Synthesizer.QUEUE_EMPTY);
synth.deallocate();
}
}
依赖:需要安装对应操作系统的TTS引擎(Windows SAPI、Mac NSSpeechSynthesizer等)。
调用WebSocket协议(低延迟、实时性强)
WebSocket + 流式TTS(如科大讯飞)
import javax.websocket.*;
import java.net.URI;
@ClientEndpoint
public class WebSocketTTSExample {
@OnMessage
public void onMessage(String message) {
// 处理返回的音频数据(base64编码)
byte[] audio = Base64.getDecoder().decode(message);
// 播放音频...
}
public static void main(String[] args) throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(
WebSocketTTSExample.class,
URI.create("wss://tts-api.xxx.com/ws")
);
session.getBasicRemote().sendText("需要合成的文本");
}
}
| 方案 | 适用场景 | 网络依赖 | 音质 | 延迟 | 成本 | 中文支持 |
|---|---|---|---|---|---|---|
| FreeTTS | 离线、英文 | 无 | 差 | 低 | 免费 | 差 |
| MaryTTS | 离线、多语言 | 无 | 中等 | 低 | 免费 | 一般 |
| 百度/阿里云 | 在线、高质量中文 | 需要 | 优秀 | 中等 | 按量付费 | 优秀 |
| Google Cloud | 在线、多语言 | 需要 | 优秀 | 中等 | 按量付费 | 好 |
| Windows原生 | Windows环境 | 无 | 良好 | 低 | 免费 | 好(Win10+) |
推荐选择
- 普通中文应用:使用 百度语音合成(免费额度足够测试,付费便宜)
- 需要离线:使用 MaryTTS 或 Windows原生TTS
- 国际化应用:使用 Google Cloud TTS 或 Azure Speech
- 极高实时性:使用 WebSocket流式方案(如科大讯飞)
根据你的具体需求(是否允许网络、预算、语音质量要求、语言)选择最合适的方案即可,如果需要更具体的集成代码示例,可以告诉我你的使用场景,我可以提供更详细的指导。