文字转语音(二)Windows PowerShell执行指令

项目中有相关的功能,就简单研究了一下。

方法原理

  1. Java 通过Runtime类执行 PowerShell 命令
  2. PowerShell 使用.NET 的System.Speech.Synthesis库实现 TTS

使用说明

  1. 系统要求
    仅限 Windows 系统
    需要安装.NET Framework 3.0+(一般 Windows 10/11 已内置)
  2. 语音包支持
    中文需要安装中文语音包(控制面板 → 语音识别 → 文本到语音)
    英文默认支持
  3. 功能扩展
    (1)调整语速
$speak.Rate = 2;  # -10到10的数字
	(2)保存为音频文件
$speak.SetOutputToWaveFile(\"C:\\output.wav\");
$speak.Speak(\"%s\");

优缺点

文字转语音(二)Windows PowerShell执行指令_第1张图片

代码实现

  /**
     * 使用powershell实现文字转语音文件
     *
     * @param text
     */
    public static void textToSpeech(String text) {
        // 转义引号和特殊字符
        String escapedText = text
                .replace("\"", "\\\"")
                .replace("'", "''")
                .replace("$", "`$");

        // 构建PowerShell命令
        String command = String.format(
                "Add-Type -AssemblyName System.speech; " +
                        "$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; " +
                        //保存语音文件到指定目录
                        //"$speak.SetOutputToWaveFile(\\\"D:\\\\output.wav\\\");" +
                        "$speak.Speak('\"%s\"') ;",
                escapedText
        ); 
        try {
            // 执行PowerShell命令
            ProcessBuilder pb = new ProcessBuilder(
                    "powershell.exe",
                    "-Command",
                    command
            );
            Process process = pb.start();
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                System.err.println("执行出错,错误码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

生成文件效果

测试文本:123456879101112,莫愁前路无知己,天下谁人不识君,good morning
具体效果参考绑定的资源文件。

你可能感兴趣的:(#,文字转语音,java,文字转语音)