使用Vue.js和Element UI自定义audio音频播放器进度条

本文将介绍如何使用Vue.js和Element UI的<el-slider>组件为<audio>元素创建一个自定义进度条。

代码示例

以下是完整的代码示例:

<template>
  <div class='audio-player'>
    <el-button icon='el-icon-arrow-left' @click='playPrevious'></el-button>
    <el-button icon='el-icon-arrow-right' @click='playNext'></el-button>
    <el-slider :min='0' :max='duration' v-model='currentTime' @input='seekTo'></el-slider>
    <audio ref='audioPlayer' @timeupdate='updateCurrentTime'></audio>
  </div>
</template>

<script>
export default {
  data() {
    return {
      playlist: [
        // 歌曲列表
        { name: 'Song 1', url: 'path/to/song1.mp3' },
        { name: 'Song 2', url: 'path/to/song2.mp3' },
        { name: 'Song 3', url: 'path/to/song3.mp3' },
        // 添加更多歌曲...
      ],
      currentSongIndex: 0, // 当前播放的歌曲索引
      currentTime: 0, // 当前播放时间
      duration: 0, // 歌曲总时长
    };
  },
  methods: {
    playPrevious() {
      if (this.currentSongIndex > 0) {
        this.currentSongIndex--;
        this.playSong();
      }
    },
    playNext() {
      if (this.currentSongIndex < this.playlist.length - 1) {
        this.currentSongIndex++;
        this.playSong();
      }
    },
    playSong() {
      const audio = this.$refs.audioPlayer;
      audio.pause();
      audio.src = this.playlist[this.currentSongIndex].url;
      audio.load();
      audio.play();
    },
    updateCurrentTime() {
      const audio = this.$refs.audioPlayer;
      this.currentTime = audio.currentTime;
      this.duration = audio.duration;
    },
    seekTo() {
      const audio = this.$refs.audioPlayer;
      audio.currentTime = this.currentTime;
    },
  },
};
</script>

<style>
.audio-player {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

代码解释

  1. <el-slider>组件: 我们使用<el-slider>组件来创建进度条。
    • :min='0':max='duration'属性设置滑块的最小值和最大值,分别对应音频的开始时间和总时长。
    • v-model='currentTime'将滑块的值绑定到currentTime数据属性,实现双向数据绑定。
    • @input='seekTo'事件监听滑块值的变化,并在值变化时调用seekTo方法。
  2. currentTimeduration数据属性:
    • currentTime存储当前播放时间。
    • duration存储歌曲总时长。
  3. playSong方法:
    • 该方法用于播放歌曲,并添加了@timeupdate事件监听器,在音频播放时更新currentTimeduration的值。
  4. updateCurrentTime方法:
    • 该方法在音频播放时被@timeupdate事件调用,用于更新currentTimeduration的值。
  5. seekTo方法:
    • 该方法在<el-slider>的值发生变化时被调用,用于设置音频的播放进度。

总结

通过上述步骤,我们成功地使用Vue.js和Element UI创建了一个自定义的audio音频播放器进度条。你可以根据自己的需求对样式和功能进行进一步的自定义。

Vue.js自定义audio音频播放器进度条教程

原文地址: https://www.cveoy.top/t/topic/uRw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录