TTS 返回语音优化

This commit is contained in:
2025-10-19 17:01:13 +08:00
parent a75d2dd985
commit a3ef5d1959
3 changed files with 26 additions and 45 deletions

View File

@@ -144,11 +144,6 @@ public class ChatWebSocketHandler {
log.info("3、开始进行AI回答时间:{}",System.currentTimeMillis()/1000);
//持续返回数据流给客户端
try {
File inputFile = new File(resultPathUrl);
File outputFile = new File(resultPathUrl);
// 设置去除尾部的秒数
float removeSeconds = 0.25f; // 去除最后5秒
trimEndByTime(inputFile, outputFile, removeSeconds);
//文件转换成文件流
ByteBuffer outByteBuffer = convertFileToByteBuffer(resultPathUrl);
//发送文件流数据
@@ -410,44 +405,5 @@ public class ChatWebSocketHandler {
}
// 裁剪音频文件,去除最后多少秒
public void trimEndByTime(File inputFile, File outputFile, float removeSeconds) {
try {
// 获取音频输入流
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile);
AudioFormat format = audioInputStream.getFormat();
// 获取音频文件的总帧数
long totalFrames = audioInputStream.getFrameLength();
// 计算音频文件的总时长(秒)
float totalDuration = totalFrames / format.getSampleRate();
// 计算新的结束位置(去除指定的时间后)
long newEndFrame = (long) ((totalDuration - removeSeconds) * format.getSampleRate());
// 确保裁剪的结束帧在合理范围内
if (newEndFrame < 0) {
System.out.println("去除的时间超过了音频的总时长");
return;
}
// 创建一个新的输入流,裁剪音频数据
AudioInputStream trimmedStream = new AudioInputStream(
audioInputStream,
format,
newEndFrame
);
// 创建新的文件并保存裁剪后的音频
AudioSystem.write(trimmedStream, AudioFileFormat.Type.WAVE, outputFile);
System.out.println("裁剪后的音频已保存到: " + outputFile.getAbsolutePath());
audioInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}