返回

与Vue一起唱歌-打造属于自己的音乐播放器

前端

音乐是人们生活中不可缺少的一部分。无论是工作、学习还是休息,音乐都能陪伴我们左右,为我们带来愉悦的心情。然而,市面上的音乐播放器大多千篇一律,无法满足个性化的需求。如果你想拥有一个独一无二的音乐播放器,不妨跟着本指南一步一步来动手制作吧!

1. 构建播放器界面

首先,我们需要创建一个播放器界面。你可以使用Vue.js自带的组件,也可以自己设计组件。这里,我们使用Vue.js自带的组件来构建一个简单的播放器界面。

<template>
  <div>
    <div class="player">
      <audio ref="audio" :src="currentSong.url"></audio>
      <div class="controls">
        <button @click="playOrPause">播放/暂停</button>
        <button @click="seekBackward">后退</button>
        <button @click="seekForward">前进</button>
      </div>
    </div>
    <div class="playlist">
      <ul>
        <li v-for="song in songs" @click="selectSong(song)">
          {{ song.name }}
        </li>
      </ul>
    </div>
  </div>
</template>
export default {
  data() {
    return {
      songs: [],
      currentSong: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
    };
  },
  methods: {
    playOrPause() {
      this.isPlaying ? this.audio.pause() : this.audio.play();
      this.isPlaying = !this.isPlaying;
    },
    seekBackward() {
      this.audio.currentTime -= 10;
    },
    seekForward() {
      this.audio.currentTime += 10;
    },
    selectSong(song) {
      this.currentSong = song;
      this.audio.src = song.url;
      this.audio.play();
    },
  },
  mounted() {
    this.songs = [
      { name: 'Song 1', url: 'https://example.com/song1.mp3' },
      { name: 'Song 2', url: 'https://example.com/song2.mp3' },
      { name: 'Song 3', url: 'https://example.com/song3.mp3' },
    ];
    this.currentSong = this.songs[0];
    this.audio.play();
  },
};

2. 连接歌曲搜索接口

接下来,我们需要连接歌曲搜索接口,以便能够搜索和播放歌曲。这里,我们使用Autumnfish提供的歌曲搜索接口。

export default {
  data() {
    return {
      songs: [],
      currentSong: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
    };
  },
  methods: {
    searchSongs(query) {
      const url = 'https://autumnfish.cn/search';
      const params = { keywords: query };
      axios.get(url, { params })
        .then(response => {
          this.songs = response.data.result.songs;
        })
        .catch(error => {
          console.error(error);
        });
    },
    playOrPause() {
      this.isPlaying ? this.audio.pause() : this.audio.play();
      this.isPlaying = !this.isPlaying;
    },
    seekBackward() {
      this.audio.currentTime -= 10;
    },
    seekForward() {
      this.audio.currentTime += 10;
    },
    selectSong(song) {
      this.currentSong = song;
      this.audio.src = song.url;
      this.audio.play();
    },
  },
  mounted() {
    this.audio.addEventListener('timeupdate', () => {
      this.currentTime = this.audio.currentTime;
      this.duration = this.audio.duration;
    });
  },
};

3. 完成音乐播放器

现在,我们的音乐播放器已经基本完成了。你可以通过搜索框搜索歌曲,然后点击歌曲列表中的歌曲即可播放。你还可以控制播放、暂停、快进、快退等操作。

如果你想让音乐播放器更加个性化,可以自己设计播放器界面,或者添加更多的功能。例如,你可以添加一个歌词显示区,或者添加一个专辑封面显示区。

至此,你已经拥有了一个完全属于自己的音乐播放器了。快去分享给你的朋友们吧!