uniapp 安卓 苹果 实现文字转语言
注意:
1:首先需要判断设备类型是安卓还是苹果,从而调用不同的方法;
2:安卓文字转语言是需要转码,否则能听见声音但不知道她说啥!!😩
3:封装安卓和iOS转语音时一定要把音量设置大一点😩😩😩😩
步骤
1:封装安卓文字转码
changeEnCode(str) {
let res = []
for (let i = 0; i < str.length; i++) {
// 这个不是正常的encodeUnicode 颠倒了大小端的位置
res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-2) + ("00" + str.charCodeAt(i).toString(16)).slice(-
4, -2)
}
let strCode = "\\u" + res.join("\\u")
strCode = strCode.replace(/\\/g, "%")
return unescape(strCode)
},
2:封装安卓文字转语音方法
AndriodSpeechToVoice: function(text) {
var main = plus.android.runtimeMainActivity();
var SpeechUtility = plus.android.importClass('com.iflytek.cloud.SpeechUtility');
SpeechUtility.createUtility(main, 'appid=5c2c6d5f');
var SynthesizerPlayer = plus.android.importClass('com.iflytek.cloud.SpeechSynthesizer');
var play = SynthesizerPlayer.createSynthesizer(main, null);
play.startSpeaking(this.changeEnCode(text), null); //这里要用到上一步封装的文字转码
},
3:封装ios文字转语言的方法(ios不需要转码)
iosSpeechToVoice: function(text) {
var AVSpeechSynthesizer = plus.ios.importClass('AVSpeechSynthesizer');
var AVSpeechUtterance = plus.ios.importClass('AVSpeechUtterance');
var AVSpeechSynthesisVoice = plus.ios.import('AVSpeechSynthesisVoice');
var sppech = new AVSpeechSynthesizer();
var voice = AVSpeechSynthesisVoice.voiceWithLanguage('zh-CN');
var utterance = AVSpeechUtterance.speechUtteranceWithString(text);
// utterance.plusSetAttribute("rate",30.1);
utterance.setVoice(voice);
sppech.speakUtterance(utterance);
//停止
sppech.stopSpeakingAtBoundary(0);
//暂停
sppech.pauseSpeakingAtBoundary(90);
//继续
sppech.continueSpeaking(90);
plus.ios.deleteObject(voice);
plus.ios.deleteObject(utterance);
plus.ios.deleteObject(sppech);
},
3:封装统一调用的方法(这里要判断设备的类型,从而调用安卓或ios即可)
say(text) {
let _this = this
uni.getSystemInfo({
success: res => {
console.log(JSON.stringify(res.platform));
if (res.platform === 'android') {
_this.AndriodSpeechToVoice(text); //是安卓
} else if (res.platform === 'ios') {
_this.iosSpeechToVoice(text); //ios
}
}
});
},
4:使用:
this.say(“你想转语言的文字”) 执行封装好的say()方法即可。