博主最近接到客户需求,要在网页上实时播放某些信息,于是找到了腾讯云的实时语音合成,在这个过程中遇到了一些问题,因此记录下来,希望能帮助到跟我有一样困扰的人,如果有什么不对的地方,欢迎指正。
腾讯云语音合成文档
可以看到这里有基础语音合成和实时语音合成,我这里用的是实时语音合成,并且腾讯云支持在线生成代码,非常方便。
API Explorer - 云API
进入页面后只需要输入一些参数,即可生成代码并且在线调试。
以下是我生成的代码,只传了一些必要的参数
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.tts.v20190823.TtsClient;
import com.tencentcloudapi.tts.v20190823.models.*;
public class TextToVoice
{
public static String textToVoice(String text){
try{
Credential cred = new Credential("AKIDMR*********", "5x71f5F9n*********");
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("tts.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
TtsClient client = new TtsClient(cred, "ap-nanjing", clientProfile);
TextToVoiceRequest req = new TextToVoiceRequest();
req.setModelType(0L);
req.setSessionId(System.currentTimeMillis()+"");//session_id
req.setText(text);//文本
// req.setSpeed(0F);
// req.setPrimaryLanguage(1L);
// req.setVoiceType(101004L);
// req.setVolume(5F);
// req.setSampleRate(16000L);
// req.setCodec("wav");
TextToVoiceResponse resp = client.TextToVoice(req);
return TextToVoiceResponse.toJsonString(resp);
} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
return null;
}
}
后台直接在main方法中调用测试很顺利,但是从页面传入中文字符再调用该方法直接抛出异常(英文和数字很正常)
[TencentCloudSDKException]message:InvalidParameter.InvalidText-Please check your text, which hasn't valid words or has invalid words. requestId:f876aaa7-4dca-4b00-87aa-b90da756b35d
根据文档说明,是请求的文本含有非法字符,我本以为是字符串编码的问题,于是转换了字符串的编码又测试,发现还是不行,这个问题足足卡了我两天,最后设置了get方式的请求,成功
httpProfile.setReqMethod("GET");
但是官方文档中说了只支持POST请求,所以问题虽然解决了,还是不知道什么原因
页面播放语音的代码
<audio id="my" autoplay="autoplay" hidden controls src="" ></audio>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "*********",
data: {text: ****},
async: false,
success : function(data) {
var obj = JSON.parse(data);
var base64 = obj.Audio;
$("#my").attr("src","data:audio/wav;base64,"+base64);
}
});
</script>
后台传回来的是Base64编码的音频文件,直接播放即可。
后续:
本来至此在浏览器中测试就没什么问题了,但是客户那边需要在电视大屏上播放,于是又打包成app安装到电视上,结果发现没有声音,原来是app内置的浏览器关闭了自动播放功能,根据网上找到的方案顺利解决了问题。
这里放上链接:https://www.jianshu.com/p/8f6448f12f24