<template>
<div style="display:flex;align-items: center;margin-bottom:2px">
<audio
ref="audio"
class="dn"
:src="audioLink"
preload="none"
@ended="onended"
@play="onPlay"
@pause="onPause"
></audio>
<i
style="font-size:20px;cursor:pointer;color:#C0C4CC"
type="text"
:class="audio.playing?'el-icon-video-pause zanting':'el-icon-video-play'"
@click="startPlay"></i>
<el-button
type="text"
style="margin-left:5px"
@click="download(realUrl)"
>
下载
</el-button>
</div>
</template>
<script>
import globalConfig from '../../shared/config.js'
export default {
name: 'VueAudio',
props: {
//需要播放下载字符串
vocabulary:{
type: String,
default: '',
}
},
data() {
return {
audio: {
playing: false,
speed: 1,
preload: 'auto'
},
audioLink:''
}
},
methods: {
// 开始播放
async startPlay() {
let url = globalConfig.serverUrl + '/ability-api/tts/sync?format=mp3&spd=0&pit=0&vol=0'
this.axios({
method:'post',
data:{
text:this.vocabulary
},
url:url,
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json' },
}).then((response) => {
let blob = new Blob([response]);
this.audioLink = URL.createObjectURL(blob)
this.$nextTick(()=>{
this.$refs.audio.play()
})
}).catch((err) => {
console.log(err);
});
},
// 暂停
pausePlay() {
this.$refs.audio.pause()
},
// 当音频暂停
onPause () {
this.audio.playing = false
},
//播放完成
onended(){
console.log('播放完成了-----------');
this.audio.playing = false
},
// 当音频开始播放
onPlay (res) {
this.audio.playing = true
let target = res.target
let audios = document.getElementsByTagName('audio');
// 只播放一个
[...audios].forEach((item) => {
if(item !== target){
item.pause()
}
})
},
async download(){
let url = globalConfig.serverUrl + '/ability-api/tts/sync?format=mp3&spd=0&pit=0&vol=0'
this.axios({
method:'post',
data:{
text:this.vocabulary
},
url:url,
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json' },
}).then((response) => {
let blob = new Blob([response]);
this.audioLink= URL.createObjectURL(blob)
this.downloadAudio();
}).catch((err) => {
console.log(err);
});
},
downloadAudio(){
const a = document.createElement('a');
a.setAttribute('href', this.audioLink); //a.href='文件链接'
a.setAttribute('download', `合成音频-${this.vocabulary}.mp3`); //a.download='文件名'
a.click();
}
},
}
</script>
<style scoped>
.zanting{
color: red;
}
</style>
vue音频播放+下载
最新推荐文章于 2024-06-06 15:08:23 发布