uniapp 播放文字 调用百度文字转语音,并播放

最近接到一个功能就是uniapp扫码,语音提示,翻遍了整个插件库,基本上都是收费的,或者就是各种的不支持低版本安卓,百度了好久,才找到解决方法:就是调用百度的接口生成MP3音频进行播放,废话不多说直接上代码。

function speak(text) {
	// 构建请求URL
	const url = 'https://tts.baidu.com/text2audio.mp3?tex=' + text +
		'&cuid=baike&amp&lan=ZH&amp&ctp=1&amp&pdt=301&amp&vol=100&amp&rate=32&amp&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("帅哥,你好")

这样就可以直接使用了,真的很简单。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值