一、基础
基于springboot
二、正文
2.1 引入依赖
<!--腾讯文本转语音-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-speech-sdk-java</artifactId>
<version>1.0.12</version>
</dependency>
2.2 主类
import com.jisudz.ai.virtual.soul.entity.VoiceEntity;
import com.tencent.SpeechClient;
import com.tencent.tts.model.SpeechSynthesisRequest;
import com.tencent.tts.service.SpeechSynthesizer;
import java.io.File;
/**
* 简述:腾讯文本转语音
* 日期: 2022/12/26
* 作者:
*/
public class TencentToVoice {
private static final String APP_ID = "腾讯云获取";
private static final String SECRET_ID = "腾讯云获取";
private static final String SECRET_KEY = "腾讯云获取";
public static void changeToVoice(){
SpeechClient speechClient = SpeechClient.newInstance(APP_ID, SECRET_ID, SECRET_KEY);
SpeechSynthesisRequest request = SpeechSynthesisRequest.initialize();
// 语音格式,默认为wav还支持pcm和mp3,默认wav测试有问题,所以这里用pcm,获取后再转为wav
request.setCodec("pcm");
// 发音人
request.setVoiceType(1017);
// 音量,默认为0
request.setVolume(0);
SpeechSynthesizer speechSynthesizer =
speechClient.newSpeechSynthesizer(request, new MySpeechSynthesizerListener());
speechSynthesizer.synthesis(voiceEntity.getVoiceTxt());
}
}
2.3 语音合成过程监听器
import com.tencent.tts.model.SpeechSynthesisResponse;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.utils.PcmUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 简述:腾讯文本转语音过程监听器
* 日期: 2022/12/29
* 作者:
*/
public class MySpeechSynthesizerListener extends SpeechSynthesisListener {
private AtomicInteger sessionId = new AtomicInteger(0);
@Override
public void onComplete(SpeechSynthesisResponse speechSynthesisResponse) {
System.out.println("onComplete");
if (speechSynthesisResponse.getSuccess()) {
byte[] audio = speechSynthesisResponse.getAudio();
int rspLen = audio.length;
byte[] wav = new byte[44 + rspLen];
PcmUtils.Pcm2WavBytes(audio, wav, 16000, 1, 16);
File wavFile = new File("111.wav");
try {
FileOutputStream out = new FileOutputStream(wavFile, false);
out.write(wav);
out.close();
} catch (IOException e){
System.out.println("保存语音文件出现错误!");
}
}
System.out.println("结束:" + speechSynthesisResponse.getSuccess() + " " + speechSynthesisResponse.getCode()
+ " " + speechSynthesisResponse.getMessage() + " " + speechSynthesisResponse.getEnd());
}
@Override
public void onMessage(byte[] bytes) {
System.out.println("onMessage length:" + bytes.length);
sessionId.incrementAndGet();
}
@Override
public void onFail(SpeechSynthesisResponse speechSynthesisResponse) {
System.out.println("onFail");
System.out.println(speechSynthesisResponse.getCode());
System.out.println(speechSynthesisResponse.getMessage());
}
}
三、资料
- 代码参考腾讯云官网语音合成:语音合成Java SDK
- SpeechSynthesisRequest 更多参数参考:SpeechSynthesisRequest 参数
- 错误码参考:错误码