本文目录导读:

我来为您提供几个Java语音合成的案例,涵盖不同的实现方式。
使用FreeTTS(开源语音合成引擎)
Maven依赖
<dependency>
<groupId>net.sf.sociaal</groupId>
<artifactId>freetts</artifactId>
<version>1.2.2</version>
</dependency>
基础案例
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTSCase {
public static void main(String[] args) {
// 获取语音管理器
VoiceManager voiceManager = VoiceManager.getInstance();
// 获取可用的语音
String[] voices = voiceManager.getVoiceNames();
System.out.println("可用的语音:");
for (String voice : voices) {
System.out.println("- " + voice);
}
// 选择语音
Voice voice = voiceManager.getVoice("kevin16");
if (voice != null) {
// 分配资源
voice.allocate();
// 设置语速(默认100)
voice.setRate(150);
// 设置音量(0-1)
voice.setVolume(0.8f);
// 设置音高(默认100)
voice.setPitch(100);
// 开始说话
voice.speak("你好,欢迎使用Java语音合成!");
voice.speak("This is a text to speech example.");
// 释放资源
voice.deallocate();
} else {
System.out.println("无法获取语音对象");
}
}
}
使用百度语音合成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 com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import org.json.JSONObject;
public class BaiduTTS {
// 设置APPID/AK/SK
private static final String APP_ID = "您的AppID";
private static final String API_KEY = "您的API Key";
private static final String SECRET_KEY = "您的Secret Key";
public static void main(String[] args) {
// 初始化一个AipSpeech对象
AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
// 调用语音合成
TtsResponse res = client.synthesis("你好,世界!", "zh", 1, null);
byte[] data = res.getData();
JSONObject resJson = res.getResult();
if (data != null) {
try {
// 保存音频文件
Util.writeBytesToFileSystem(data, "output.mp3");
System.out.println("音频文件已生成:output.mp3");
} catch (IOException e) {
e.printStackTrace();
}
}
if (resJson != null) {
System.out.println("返回信息:" + resJson.toString());
}
}
// 高级用法:设置参数
public static void advancedExample() {
AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
// 设置可选参数
HashMap<String, Object> options = new HashMap<>();
options.put("spd", "5"); // 语速,取值0-15,默认为5中语速
options.put("pit", "5"); // 音调,取值0-15,默认为5中语调
options.put("vol", "5"); // 音量,取值0-15,默认为5中音量
options.put("per", "4"); // 发音人,4为情感女声,0为普通女声,1为普通男声,3为情感男声
TtsResponse res = client.synthesis("这是一个高级语音合成示例", "zh", 1, options);
byte[] data = res.getData();
if (data != null) {
try {
Util.writeBytesToFileSystem(data, "advanced_output.mp3");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用Java Sound API(基础音频播放)
import javax.sound.sampled.*;
import java.io.*;
public class AudioPlayer {
public static void playWav(String filePath) {
try {
// 打开音频输入流
AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(filePath));
// 获取音频格式
AudioFormat format = audioStream.getFormat();
// 创建数据行信息
DataLine.Info info = new DataLine.Info(Clip.class, format);
// 创建音频行
Clip audioClip = (Clip) AudioSystem.getLine(info);
// 打开音频流
audioClip.open(audioStream);
// 开始播放
audioClip.start();
// 等待播放完成
Thread.sleep(audioClip.getMicrosecondLength() / 1000);
// 关闭资源
audioClip.close();
audioStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 实时合成并播放
public static void synthesizeAndPlay(String text) {
// 这里可以集成FreeTTS或百度API
// 示例:使用FreeTTS实时播报
VoiceManager voiceManager = VoiceManager.getInstance();
Voice voice = voiceManager.getVoice("kevin16");
if (voice != null) {
voice.allocate();
voice.speak(text);
voice.deallocate();
}
}
}
完整的语音合成工具类
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import java.util.HashMap;
import java.util.Map;
public class TTSUtil {
private static TTSUtil instance;
private Voice voice;
private Map<String, Voice> voiceCache = new HashMap<>();
private TTSUtil() {
initVoice();
}
public static synchronized TTSUtil getInstance() {
if (instance == null) {
instance = new TTSUtil();
}
return instance;
}
private void initVoice() {
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin16");
if (voice != null) {
voice.allocate();
}
}
public void speak(String text) {
if (voice != null) {
voice.speak(text);
}
}
public void speakAsync(String text) {
new Thread(() -> speak(text)).start();
}
public void setVolume(float volume) {
if (voice != null) {
voice.setVolume(Math.max(0, Math.min(1, volume)));
}
}
public void setRate(int rate) {
if (voice != null) {
voice.setRate(rate);
}
}
public void cleanup() {
if (voice != null) {
voice.deallocate();
}
}
// 示例使用
public static void main(String[] args) {
TTSUtil tts = TTSUtil.getInstance();
// 同步播报
tts.speak("正在初始化系统...");
// 异步播报
tts.speakAsync("任务已完成");
// 调整参数
tts.setVolume(0.8f);
tts.setRate(120);
tts.speak("调整后的语音播报");
// 清理资源
tts.cleanup();
}
}
Web应用程序集成示例(Spring Boot)
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@RestController
@RequestMapping("/api/tts")
public class TTSController {
@PostMapping("/speak")
public ResponseEntity<byte[]> speak(@RequestParam String text) {
try {
// 使用百度API合成语音
AipSpeech client = new AipSpeech("APP_ID", "API_KEY", "SECRET_KEY");
HashMap<String, Object> options = new HashMap<>();
options.put("spd", "5");
options.put("per", "0");
TtsResponse res = client.synthesis(text, "zh", 1, options);
byte[] data = res.getData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "speech.mp3");
return ResponseEntity.ok()
.headers(headers)
.body(data);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@PostMapping("/play")
public String playVoice(@RequestParam String text) {
TTSUtil tts = TTSUtil.getInstance();
tts.speak(text);
return "正在播报:" + text;
}
}
注意事项
- FreeTTS:中文支持有限,推荐使用英文
- 百度API:需要申请百度AI账号和API Key
- 语音质量:在线服务通常效果更好
- 资源管理:使用完毕后及时释放语音资源
- 并发处理:多线程使用时注意同步
这些案例涵盖了从基础到高级的不同使用场景,您可以根据实际需求选择合适的方案。