最近接到一个功能就是uniapp扫码,语音提示,翻遍了整个插件库,基本上都是收费的,或者就是各种的不支持低版本安卓,百度了好久,才找到解决方法:就是调用百度的接口生成MP3音频进行播放,废话不多说直接上代码。
function speak(text) {
// 构建请求URL
const url = 'https://tts.baidu.com/text2audio.mp3?tex=' + text +
'&cuid=baike&&lan=ZH&&ctp=1&&pdt=301&&vol=100&&rate=32&&per=0&spd=10&pit=undefined';
if (typeof Audio !== 'undefined') {
// H5 平台
const audio = new Audio(url);
audio.play();
} else if (typeof wx !== 'undefined' && wx.createInnerAudioContext) {
// 微信小程序平台
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src = url;
innerAudioContext.play();
} else if (typeof plus !== 'undefined' && plus.audio) {
// App(原生)平台
const player = plus.audio.createPlayer(url);
player.play(function() {
console.log('Play success');
}, function(e) {
console.log('Play failed: ' + e.message);
});
} else if (typeof my !== 'undefined' && my.createInnerAudioContext) {
// 支付宝小程序平台
const innerAudioContext = my.createInnerAudioContext();
innerAudioContext.src = url;
innerAudioContext.play();
} else if (typeof swan !== 'undefined' && swan.createInnerAudioContext) {
// 百度小程序平台
const innerAudioContext = swan.createInnerAudioContext();
innerAudioContext.src = url;
innerAudioContext.play();
} else if (typeof tt !== 'undefined' && tt.createInnerAudioContext) {
// 字节跳动小程序平台
const innerAudioContext = tt.createInnerAudioContext();
innerAudioContext.src = url;
innerAudioContext.play();
} else {
console.error('Unsupported platform or Audio object is not defined');
}
}
export default {
speak
}
上面代码是我封装的调用百度的方法
在你需要使用的uniapp页面进行调用
import speak from "@/utils/speak.js"
speak.speak("帅哥,你好")
这样就可以直接使用了,真的很简单。