最近写一个文字转语音的页面,语音转换完成后要播放,于是就用上了vue-aplayer
安装vue-aplayer
npm install vue-aplayer –save
引入并配置aplayer组件
import Aplayer from 'vue-aplayer'
components: {
Aplayer
},
接下来就可以直接使用了
<aplayer autoplay :music="{
title: 'Preparation',
author: 'Hans Zimmer/Richard Harvey',
url: 'http://devtest.qiniudn.com/Preparation.mp3',
pic: 'http://devtest.qiniudn.com/Preparation.jpg',
lrc: '[00:00.00]lrc here\n[00:01.00]aplayer'
}">
</aplayer>
当然根据实际情况,我只需要给他一个url参数就行了
先在语音转换页面提交表单,发送post请求,将返回的VoicePath用session保存下来
submitForm(formName){
var api='http://118.25.229.125:8888/api/v1/text_voice/';
this.$http.post(api,{
//字符串
lan:this.voiceForm.content,
//音量
vol:this.voiceForm.vol,
//音调
pit:this.voiceForm.tone,
//语速
spd:this.voiceForm.speed,
//发音人
per:this.voiceForm.radio},{emulateJSON: true}).then((response)=>{
console.log(response);
this.url = response.body.VoicePath;
if(this.url){
sessionStorage.setItem('url', this.url);
this.$router.push({path:'/Player'});
}else{
alert('转换失败!');
}
},function(err){
console.log(err);
});
},
在播放页面,通过session拿到url数据,把他的值给aplayer参数就行了
结果遇到了问题,当时通过response拿到的数据是这样的
原来这个VoicePath得到的路径需要修改一下
修改成http://118.25.229.125:8888/api/v1/text_voice/?VoicePath=/home/littlecute/TEST/MP3_File/8bfa1f1e766a35e23cc6346478034ed1.mp3就可以访问了
接着又遇到一个问题,由于aplayer的参数都是先配置好的,而我的路径是等传过来之后才赋值给url,导致的结果就是参数修改成功,可是页面却不能重新渲染
试了很多解决方法,最后发现是,当页面加载的时候aplayer就开始play了,于是给他一个判断v-if,等我把获取到的url值给他之后再让他play。
下面是我的代码
html
<template>
<el-row :gutter="20">
<el-col :span="12" :offset="6" :xs="18">
<el-row :gutter="20">
<el-col :span="3" :offset="18">
<el-button type="primary" circle icon="el-icon-download" @click="downVoice()"></el-button>
</el-col>
<el-col :span="1" :offset="0">
<el-button type="info" circle icon="el-icon-close" @click="close()"></el-button>
</el-col>
</el-row>
<aplayer autoplay :music="vioce" v-if="flag" ref="aplayer">
</aplayer>
</el-col>
</el-row>
</template>
js
<script>
import Aplayer from 'vue-aplayer'
export default{
components: {
Aplayer
},
data(){
return{
flag:false,
vioce:{
title:'未知',
artist:'我',
url:'',
pic:'',
lir:'[00:00.00]lrc here\n[00:01.00]aplayer'
}
};
},
methods:{
getUrl(){
var api = "http://118.25.229.125:8888/api/v1/text_voice/";
var path = sessionStorage.getItem('url');
this.vioce.url = api + '?VoicePath=' + path
// this.$forceUpdate();强制渲染
// this.$set(this.vioce, 'url', 'http://118.25.229.125:8888/api/v1/text_voice/?VoicePath=/home/littlecute/TEST/MP3_File/576b5fd9437a955018efc3ea89178c9d.mp3');
this.flag = true;
},
downVoice(){
window.location.href = this.vioce.url;
},
close(){
this.$router.push({path:'/home'})
}
},
mounted(){
this.getUrl();
}
}
</script>