uniapp将文章内容转为音频并朗诵 您所在的位置:网站首页 朗读当前页面的文章 uniapp将文章内容转为音频并朗诵

uniapp将文章内容转为音频并朗诵

2024-07-11 06:41| 来源: 网络整理| 查看: 265

将文章内容转为音频并朗诵

一.创建一个标签用来控制音频播放和暂停

二.全局创建一个音频对象 在这里插入图片描述

// 在js中创建音频对象 var innerAudioContext = uni.createInnerAudioContext(); innerAudioContext.autoplay = false; //不让它自动播放 innerAudioContext.src = '';

三.在获取文章内容中将文章进行处理

//contents是我的文章内容 contents = contents.replace(' ', ''); //先将内容中的空格删掉 if (contents.length > 500) { //限制播放的长度大小 this.tex = contents.substr(0, 500); var encoded = encodeURI(this.tex); //文章中如果含有%之类的符号,这一步非常重要(将一些符号转译) this.tex = encoded; } else { var encoded = encodeURI(extras); this.tex = encoded; }

四.将内容使用百度tts进行语音识别

this.src = 'https://tts.baidu.com/text2audio.mp3?tex=' + this.tex +'&cuid=baike&lan=ZH&ctp=1&pdt=301&vol=100&rate=32&per=' + this.per + '&spd=' + this.spd; //this.per为音色:设置为1,2,3,有不同的音色,this.spd为朗读的速度 innerAudioContext.src = this.src; //将生成的mp3赋值给innerAudioContext

五.在点击事件中播放音频

playMusic(){ //播放音乐 var this1 =this; innerAudioContext.play(); //直接播放 innerAudioContext.onPlay(function() { //暂停之后点击播放继续播放 if (this1.currentTime) { innerAudioContext.seek(this1.currentTime) } }) this.Music=true; }, stopMusic(){ //暂停音乐 var this1 =this; innerAudioContext.onPause(function() { console.log('暂停播放'); this1.currentTime = innerAudioContext.currentTime; }) this.Music=false; }

目前h5和APP都可以正常使用



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有