package com.tencentcloud.tts;
import com.tencent.SpeechClient;
import com.tencent.core.model.GlobalConfig;
import com.tencent.core.utils.ByteUtils;
import com.tencent.tts.model.*;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.service.SpeechSynthesizer;
import com.tencent.tts.service.SpeechSynthesisListener;
import com.tencent.tts.utils.OpusUtils;
import com.tencent.tts.utils.Ttsutils;
import java.io.*;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
* 语音合成 example
*/
public class SpeechTtsExample {
private static String codec = "pcm";
private static int sampleRate = 16000;
private static byte[] datas = new byte[0];
* 语音合成
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Properties props = new Properties();
props.load(new FileInputStream("../../config.properties"));
String appId = props.getProperty("appId");
String secretId = props.getProperty("secretId");
String secretKey = props.getProperty("secretKey");
SpeechClient client = SpeechClient.newInstance(appId, secretId, secretKey);
SpeechSynthesisRequest request = SpeechSynthesisRequest.initialize();
request.setCodec(codec);
request.setVoiceType(101007);
SpeechSynthesizer speechSynthesizer = client.newSpeechSynthesizer(request, new MySpeechSynthesizerListener());
String ttsText = "腾讯云语音合成测试";
speechSynthesizer.synthesis(ttsText);
}
public static class MySpeechSynthesizerListener extends SpeechSynthesisListener {
private AtomicInteger sessionId = new AtomicInteger(0);
@Override
public void onComplete(SpeechSynthesisResponse response) {
System.out.println("onComplete");
if (response.getSuccess()) {
if ("pcm".equals(codec)) {
Ttsutils.responsePcm2Wav(sampleRate, response.getAudio(), response.getSessionId());
}
if ("opus".equals(codec)) {
System.out.println("OPUS:" + response.getSessionId() + " length:" + response.getAudio().length);
}
}
System.out.println("结束:" + response.getSuccess() + " " + response.getCode()
+ " " + response.getMessage() + " " + response.getEnd());
}
@Override
public void onMessage(byte[] data) {
System.out.println("onMessage length:" + data.length);
sessionId.incrementAndGet();
}
@Override
public void onFail(SpeechSynthesisResponse response) {
System.out.println("onFail");
}
}
}