微信小程序实现语音合成功能

调用微信腾讯云智能语音实现智能语音播报

适用场景:小程序需要实现文本合成语音播报时

通过调用腾讯云智能语音实现

具体实现步骤

  1. 小程序登录微信公众平台
  2. 点击设置–>第三方设置–>插件管理–>添加插件
  3. 搜索腾讯云智能语音,如下图示
    在这里插入图片描述
  4. 在自己的小程序(pages.json或者app.json)添加插件:
"plugins": {
    
       // 引入插件
		"QCloudAIVoice": {
    
    
			"version": "1.3.4", //请于文档顶部【版本更新能力】中获取最新版本号
			"provider": "wx3e17776051baf153"
		}
	}
  1. 在需要使用插件的页面引入插件
let plugin = requirePlugin("QCloudAIVoice");// 引入插件
plugin.setQCloudSecret(appid, secretid, secretkey, openConsole); //设置腾讯云账号信息,其中appid是数字,secret是字符串,openConsole是布尔值(true/false),为控制台打印日志开关

  • 业务代码编写,以下为示例代码:
<scriprt>
// 创建音频组件
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = false;
innerAudioContext.src = '';
// 音频播放方法
play(id){
    
    
		var that = this;
		if(that.oldId == id && that.currentTime > 0){
    
    // 控制是否是当前已经播报过,现在处于暂停的文章
			//暂停之后点击播放继续播放
			innerAudioContext.play();
			innerAudioContext.onEnded((res) => {
    
    
			})
		}else{
    
    //新文章
			var extras = that.content;// 要播报的文本
			var lastExtras;
			// 提取汉字(由于笔者要播报的来自富文本,所以需要提取文字)
			if(extras != null && extras != ''){
    
    
				// 去掉html标签
				lastExtras = extras.replace(/<[^>]+>/g,"");
				// 只留汉字和数字
				lastExtras = lastExtras.replace(/[^\u4e00-\u9fa5_0-9]/gi,"");
			}
			if(lastExtras.length > 100){
    
    
				lastExtras = lastExtras.substr(0,100);
			}
			var encoded = encodeURI(lastExtras);
				plugin.textToSpeech({
    
    
					content: lastExtras,
					speed: 0,
					volume: 0,
					voiceType: 0,
					language: 1,
					projectId: 0,
					sampleRate: 16000,
					success: function(data) {
    
    
						let url = data.result.filePath;
						if(url && url.length > 0){
    
    
							innerAudioContext.autoplay = true;
							innerAudioContext.src = url;
							innerAudioContext.onPlay(() => {
    
    
							});
							innerAudioContext.onError((res) => {
    
    
								console.log(res.errMsg)
							});
						}
					},
					fail: function(error){
    
    
						console.log(error);
					}
				})
		}
		that.oldId = id;
	},
</script>

总结

以上就是通过调用腾讯云智能语音插件实现文本合成的步骤,文章代码仅为示例代码。

  • 具体使用可参考官方文档(需要登录,执行完第三步就看到啦)
  • 由于只支持100个汉字合成语音,如果需要合成超过100字以上的文章,需要截取处理,具体操作可以查看我的下一篇文章!
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Shiny_boy_/article/details/125932009