vue3+ts实现一个简单的音乐组件,包括播放、暂停、切换歌曲

这个组件包含了一个音频标签和三个按钮,分别用于播放、暂停和切换歌曲。在setup函数中定义了当前播放的歌曲、播放、暂停和切换歌曲的方法。

ts 复制代码
<template>
  <div>
    <audio ref="audioTag" :src="currentSong.url"></audio>
    <button @click="play">Play</button>
    <button @click="pause">Pause</button>
    <button @click="nextSong">Next Song</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';

interface Song {
  name: string;
  url: string;
}

export default defineComponent({
  setup() {
    const audioTag = ref<null | HTMLAudioElement>(null);
    const songs: Song[] = [
      { name: 'Song1', url: 'http://example.com/song1.mp3' },
      { name: 'Song2', url: 'http://example.com/song2.mp3' },
    ];

    let currentSongIndex = 0;

    const play = () => {
      if (audioTag.value) {
        audioTag.value.play();
      }
    };

    const pause = () => {
      if (audioTag.value) {
        audioTag.value.pause();
      }
    };

    const nextSong = () => {
      currentSongIndex = (currentSongIndex + 1) % songs.length;
      if (audioTag.value) {
        audioTag.value.src = songs[currentSongIndex].url;
        audioTag.value.play();
      }
    };

    return {
      currentSong: songs[currentSongIndex],
      play,
      pause,
      nextSong,
    };
  },
});
</script>

最后,在App.vue中使用这个音乐播放器组件:

ts 复制代码
<template>
  <div id="app">
    <MusicPlayer />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import MusicPlayer from './components/MusicPlayer.vue';

export default defineComponent({
  components: {
    MusicPlayer,
  },
});
</script>
相关推荐
补码缩写3 分钟前
视频跳转触发了seeked,画面就到位了吗
前端
库拉镜像AI牛牛8 分钟前
漫剧工作室量产方案:依托知漫剧 AI 短剧降本增效
大数据·服务器·前端·人工智能·语音识别
大纽耶耶15 分钟前
我把 YOLO 训练做成了网页版:需求设计与技术选型
vue.js
不可能片场17 分钟前
内容运营自动化 用相似度拦住撞车选题
前端·electron
静默回滚18 分钟前
视频进度条跳回去,先别改事件监听
前端
大纽耶耶22 分钟前
开发 YOLO 训练管理平台的 23 个实践教训
vue.js
Lank_M22 分钟前
MP4和WebM导出后为何起播与拖动不同
前端
用户55084929025625 分钟前
前端本地存储怎么选:Cookie、localStorage、sessionStorage、IndexedDB 的取舍
前端
用户55084929025625 分钟前
Git 日常命令与分支协作流程:从提交到合并的实战梳理
前端
修炼的dance25 分钟前
同一段视频没降画质为什么就快了
前端