当前位置: 首页 > 后端技术 > Node.js

使用Node中间层连接讯飞实现h5页面文章的tts(自动阅读)功能

时间:2023-04-03 18:46:29 Node.js

很多时候看文章的时候会有自动阅读文章内容的功能,请问这个功能怎么样在h5上实现?,下面以我们公司的一个基本需求为线索,看看这个需求是如何一步步实现的。经过我们产品经理的想法,做了以下功能:1.自动读取当前h5页面文章竞品——》调研发现竞品pinh5是app原生实现,而我们公司使用的是h5实现文章阅读,于是开始做h5研究,对接科大讯飞的在线语音合成研究,发现科大讯飞的在线语音合成基本可以提供相应的功能,于是决定做一个demo。测试效果1.控制台权限2.阅读文档具体代码如下newDate())/1000letparam={auf:'audio/L16;rate=16000',aue:'lame',voice_name:'小燕',speed:'50',volume:'50',pitch:'50',engine_type:'intp65',text_type:'text'}letBase64={encode:(str)=>{returnbtoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,functiontoSolidBytes(match,p1){returnString.fromCharCode('0x'+p1);}));},decode:(str)=>{//倒退:从字节流,到百分比编码,再到原始st戒指。返回decodeURIComponent(atob(str).split('').map(function(c){return'%'+('00'+c.charCodeAt(0).toString(16)).slice(-2);})。加入(''));}}letxp=Base64.encode(JSON.stringify(param))letCheckSum=md5.hex_md5(apiKey+CurTime+xp)letheaders={'X-Appid':Appid,'X-CurTime':CurTime,'X-Param':xp,'X-CheckSum':CheckSum,'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}exportfunctiongetAloud(text){//letdata={//text:encodeURI(text)//}varformdata=newFormData()formdata.append('text',text)returnaxios({baseURL:window.location.href.includes('demo')?'https://api.xfyun.cn':'/tts',method:'POST',url:'/v1/service/v1/tts',headers:{...headers},data:formdata})}经测试,返回的是二进制文件流,但是前端尝试了各种方法都没有实现流的播放。节点中间层引入节点中间层是考虑到可以把文件存起来放在cdn上缓存可以减少类似文章对科大讯飞接口的请求,减少流量的产生,所以决定加入节点中间层ps:考拉读书有点头电子服务器作为一些中间层处理主要技术栈是node+koa2+pm2constmd5=require('../lib/md5.js')constfs=require('fs')constpath=require('path')constmarked=require('marked')constrequest=require('request')letAppid=''letapiKey=''letCurTimeletparam={auf:'audio/L16;rate=16000',aue:'lame',voice_name:'x_yiping',speed:'40',volume:'50',pitch:'50',engine_type:'intp65',text_type:'text'}varb=newBuffer(JSON.stringify(param));letxp=b.toString('base64')letCheckSumletheadersexports.getAloud=asyncctx=>{CurTime=Date.parse(newDate())/1000CheckSum=md5.hex_md5(apiKey+CurTime+xp)headers={'X-Appid':Appid,'X-CurTime':CurTime,'X-Param':xp,'X-CheckSum':CheckSum,'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'}letid=ctx.request.body.idlettext=ctx.request.body.textconsole.log(ctx.query)varpostData={文本:文本}letr=request({url:'http://api.xfyun.cn/v1/service/v1/tts',//请请求的URLmethod:'POST',//请请求方法headers:headers,formData:postData},function(error,response,body){//console.log('error:',error);//如果发生错误则打印错误//console.log('statusCode:',response&&response.statusCode);//如果收到响应则打印响应状态代码//console.log('body:',body);//打印Google主页的HTML。})awaitnewPromise((resolve,reject)=>{letfilePath=path.join(__dirname,'public/')+`/${id}.mp3`constupStream=fs.createWriteStream(filePath)r.pipe(upStream)upStream.on('close',()=>{console.log('下载完成');resolve()});}).then((res)=>{ctx.body={code:200,message:'语言合成成功',data:{url:'https://fe.koalareading.com/file/'+id+'.mp3'}}})}主要是利用request的管道流概念将后台返回的二进制文件导入流中,并写入到文件中,最后返回一个url给前端播放。敬请测试//返回相同url文章的唯一id来区分,可以缓存使用https://fe.koalareading.com/file/1112.mp3来完成需要的demo