Edge-TTS是一个Python库,可以将文本转换为语音,并且支持多种语言和声音。关于安装edge-tts库可以参考edge-tts微软文本转语音库,来看看这些语音你是不是很熟悉 - 知乎 (zhihu.com)
在java中调用的完整代码如下
package com.tc.util;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* @program: sty
* @description: 文字转语音工具类
* @author: ltc
* @created: 2023/10/07 16:32
*/
@Slf4j
public class TTSUtils {
public static void easy(String txt) {
String ttsPath = "edge-tts";
// 保存地址
String saveFilePath = "D://tts-test//t1.wav";
// 选择声音模型
String soundType = "zh-CN-XiaoyiNeural";
try {
ProcessBuilder processBuilder = new ProcessBuilder(
ttsPath,
"--voice", soundType,
"--text", txt,
"--write-media",saveFilePath );
Process process = processBuilder.start();
// 等待FFmpeg进程完成
int exitCode = process.waitFor();
if (exitCode == 0) {
log.info("音频转换成功!");
// 音频的具体信息
// SoundInfo.getAudioInfo(saveFilePath);
} else {
log.error("音频转换失败!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
具体参数选择
- text = TEXT 需要转换的文本
- voice = voice 选择的语音
- rate = rate 语速
- volume=volume 音量
- output 输出文件,一般是MP3文件
音频具体信息如下
package com.tc.util;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @program: sty
* @description: 声音信息
* @author: ltc
* @created: 2023/10/07 17:31
*/
public class SoundInfo {
public static void getAudioInfo(String path) throws IOException {
File f = new File(path);
RandomAccessFile rdf = null;
rdf = new RandomAccessFile(f,"r");
System.out.println("声音尺寸: " + toInt(read(rdf, 4, 4))); // 声音尺寸
System.out.println("音频格式: " + toShort(read(rdf, 20, 2))); // 音频格式 1 = PCM
System.out.println("声道数: " + toShort(read(rdf, 22, 2))); // 1 单声道 2 双声道
System.out.println("采样率: " + toInt(read(rdf, 24, 4))); // 采样率、音频采样级别 8000 = 8KHz
System.out.println("波形的数据量: " + toInt(read(rdf, 28, 4))); // 每秒波形的数据量
System.out.println("采样帧: " + toShort(read(rdf, 32, 2))); // 采样帧的大小
System.out.println("采样位数: " + toShort(read(rdf, 34, 2))); // 采样位数
rdf.close();
}
/**
* 工具类相关
*/
public static int toInt(byte[] b) {
return ((b[3] << 24) + (b[2] << 16) + (b[1] << 8) + (b[0] << 0));
}
public static short toShort(byte[] b) {
return (short)((b[1] << 8) + (b[0] << 0));
}
public static byte[] read(RandomAccessFile rdf, int pos, int length) throws IOException {
rdf.seek(pos);
byte result[] = new byte[length];
for (int i = 0; i < length; i++) {
result[i] = rdf.readByte();
}
return result;
}
}