Java案例如何实现文字转语音?

wen python案例 2

本文目录导读:

Java案例如何实现文字转语音?

  1. 使用 FreeTTS (纯Java实现)
  2. 使用 Java Speech API (JSAPI)
  3. 调用系统语音API (Windows)
  4. 使用百度AI语音合成API (在线)
  5. 使用Google Cloud Text-to-Speech
  6. 方案对比
  7. 选择建议

我来介绍几种在Java中实现文字转语音(TTS)的常用方法:

使用 FreeTTS (纯Java实现)

FreeTTS是Java最常用的TTS库,纯Java实现,无需外部依赖。

Maven依赖

<dependency>
    <groupId>org.mobicents.external.freetts</groupId>
    <artifactId>freetts</artifactId>
    <version>1.0.2</version>
</dependency>

示例代码

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class FreeTTSSimple {
    public static void main(String[] args) {
        // 设置语音管理器
        System.setProperty("freetts.voices", 
            "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
        // 获取语音
        VoiceManager vm = VoiceManager.getInstance();
        Voice voice = vm.getVoice("kevin16");
        if (voice != null) {
            voice.allocate();
            // 设置音量和语速
            voice.setPitch(100);
            voice.setRate(150);
            voice.setVolume(8);
            // 文字转语音
            voice.speak("你好,这是一个文字转语音的示例。");
            voice.speak("欢迎使用Java TTS功能。");
            voice.deallocate();
        }
    }
}

使用 Java Speech API (JSAPI)

JSAPI是Java的语音API标准,配合FreeTTS的实现。

import javax.speech.*;
import javax.speech.synthesis.*;
import java.util.Locale;
public class JSAPITTS {
    public static void main(String[] args) {
        try {
            // 创建合成器
            Synthesizer synthesizer = Central.createSynthesizer(null);
            // 分配资源
            synthesizer.allocate();
            synthesizer.resume();
            // 设置语音
            synthesizer.getSynthesizerProperties()
                .setVoice(new Voice("kevin16", 
                    Voice.GENDER_MALE, 
                    Voice.AGE_NEUTRAL, 
                    Locale.US));
            // 合成语音
            synthesizer.speakPlainText("Hello, this is a text to speech demo.", null);
            synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
            // 释放资源
            synthesizer.deallocate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

调用系统语音API (Windows)

使用Java调用Windows的SAPI(Speech API)。

import java.io.*;
public class WindowsSAPI {
    public static void speak(String text) {
        try {
            // 创建VBScript脚本
            String script = "CreateObject(\"SAPI.SpVoice\").Speak \"" + text + "\"";
            // 创建临时VBS文件
            File tempFile = File.createTempFile("speak", ".vbs");
            FileWriter fw = new FileWriter(tempFile);
            fw.write(script);
            fw.close();
            // 执行VBS文件
            Process process = Runtime.getRuntime()
                .exec("cscript //NoLogo " + tempFile.getAbsolutePath());
            process.waitFor();
            // 删除临时文件
            tempFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        speak("你好,这是通过Windows SAPI实现的语音合成。");
    }
}

使用百度AI语音合成API (在线)

使用百度AI的在线语音合成服务。

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 java.util.HashMap;
public class BaiduTTS {
    // 设置APPID/AK/SK
    private static final String APP_ID = "你的APP_ID";
    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);
        // 设置请求参数
        HashMap<String, Object> options = new HashMap<>();
        options.put("spd", "5");     // 语速
        options.put("pit", "5");     // 音调
        options.put("vol", "5");     // 音量
        options.put("per", "0");     // 发音人
        // 调用语音合成
        TtsResponse res = client.synthesis("你好,欢迎使用百度语音合成服务。", 
            "zh", 1, options);
        byte[] data = res.getData();
        if (data != null) {
            try {
                // 保存为MP3文件
                FileOutputStream fos = new FileOutputStream("audio.mp3");
                fos.write(data);
                fos.close();
                System.out.println("语音文件已生成:audio.mp3");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

使用Google Cloud Text-to-Speech

Maven依赖

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-texttospeech</artifactId>
    <version>2.4.0</version>
</dependency>

示例代码

import com.google.cloud.texttospeech.v1.*;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
public class GoogleCloudTTS {
    public static void main(String[] args) throws Exception {
        // 初始化客户端
        try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
            // 设置文本
            SynthesisInput input = SynthesisInput.newBuilder()
                .setText("Hello, this is Google Cloud Text-to-Speech.")
                .build();
            // 设置语音参数
            VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
                .setLanguageCode("en-US")
                .setSsmlGender(SsmlVoiceGender.NEUTRAL)
                .build();
            // 设置音频参数
            AudioConfig audioConfig = AudioConfig.newBuilder()
                .setAudioEncoding(AudioEncoding.MP3)
                .build();
            // 执行语音合成
            SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(
                input, voice, audioConfig);
            // 获取音频内容
            ByteString audioContents = response.getAudioContent();
            // 保存为文件
            try (FileOutputStream out = new FileOutputStream("output.mp3")) {
                out.write(audioContents.toByteArray());
                System.out.println("语音文件已生成:output.mp3");
            }
        }
    }
}

方案对比

方案 优点 缺点
FreeTTS 纯Java实现,无需外部依赖 语音质量一般,仅支持英文
JSAPI 标准API,易于扩展 需要实现类,配置复杂
系统SAPI 音质好,支持中文 仅限Windows平台
百度AI 音质优秀,支持多种语言 需要网络,有调用限制
Google Cloud 音质极佳,功能丰富 需要付费,配置复杂

选择建议

  1. 简单快速开发:使用FreeTTS
  2. Windows环境:使用系统SAPI
  3. 需要高质量语音:使用百度AI或Google Cloud
  4. 跨平台需求:使用FreeTTS或在线API

根据你的具体需求选择合适的方案即可!

抱歉,评论功能暂时关闭!