el-table中使用audio

1,943 阅读1分钟

尝试了 aplayer Vue-APlayer 两款插件 发现在项目中不太适用 所以就用 audio 实现了一下需求。

需求:

使用 el-table 展示查询数据 需要对每一条数据中的音频进行操作 播放结束自动播放下一条 放上效果图如下:

实现:

template:

<el-table-column label="操作" width="130">
    <template slot-scope="scope">
        <el-button
            v-if="scope.row.showStart" 
            @click="play(scope.row)" 
            icon="el-icon-video-play" 
            type="info" 
            size="mini" 
            plain 
            round
        >播放</el-button>
        <el-button
            v-else 
            @click="pause(scope.row)" 
            icon="el-icon-video-pause" 
            type="success" 
            size="mini" 
            plain 
            round
        >暂停</el-button>
        <audio :ref="scope.row.recordingId" @ended="over(scope.row)">
            <source :src="scope.row.recordingUrl"/>
        </audio>
    </template>
</el-table-column>
  • 只要不给 audio 标签 设置 controls 则不向用户显示控件
  • showStart 用于控制切换播放和暂停按钮
  • 给遍历出来的 audio 设置 ref 唯一主键 recordingId

JavaScript:

play(data){
    this.tabelList.map( item =>{
        if(data.recordingId === item.recordingId){ //获取点击的当前项
            item.showStart = false //将当前按钮显示为暂停
            if(!item.showStart){
                this.$refs[data.recordingId].play(); 
            }
        }else{ // 非当前项的全部暂停
            this.$refs[item.recordingId].pause();
            item.showStart = true; //将按钮显示为播放
        }
    })
},
pause(data){
    data.showStart = true;
    this.$refs[data.recordingId].pause();
},
over(data){ //播放结束执行
    data.showStart = true; //播放结束将按钮显示为播放
    this.tabelList.map((item,index)=>{
        if(data.recordingId === item.recordingId){
            if(this.tabelList[index + 1]){ //判断是否当前项播放完毕还有下一项
                this.tabelList[index + 1].showStart = false; //将下一项的按钮显示为暂停
                this.$refs[this.tabelList[index + 1].recordingId].play();//开启下一个
            }
        }
    })
}
  • play() 点击播放
  • pause() 暂停
  • over() 当前音频播放完毕自动播放下一条