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

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

<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中使用这个音乐播放器组件:


<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>

原文链接:https://juejin.cn/post/7342335589742542899 作者:前端fighter

(0)
上一篇 2024年3月5日 上午10:48
下一篇 2024年3月5日 上午10:58

相关推荐

发表回复

登录后才能评论