Home > Web Front-end > Vue.js > body text

Building a modern music player: the golden combination of Vue and NetEase Cloud API

王林
Release: 2023-07-18 14:21:18
Original
631 people have browsed it

Building a modern music player: the golden combination of Vue and NetEase Cloud API

Introduction:
Music plays an important role in our lives, and a modern music player allows us to Listen to our favorite songs anywhere. In this article, we will use Vue.js and NetEase Cloud API to show how to build a modern music player. Through this example, you will learn how to use the componentization idea of ​​Vue.js and the data acquisition and interaction of NetEase Cloud API to build a feature-rich music player.

Technology stack:
Before we begin, we will introduce the technology stack we will use. Vue.js is a popular JavaScript framework that adopts the idea of ​​componentization, allowing us to easily build reusable and easy-to-maintain user interfaces. The NetEase Cloud API provides a wealth of music data, including songs, albums, singers and other information, as well as music playback and control functions.

Project preparation:
First, we need to create a Vue project. You can use the Vue CLI to create a new project:

vue create music-player
Copy after login

During the process of creating the project, you can choose different configuration options as needed.

Next, we need to install some necessary dependency packages. In the terminal, switch to the root directory of the project and execute the following commands:

cd music-player
npm install axios vuex vuex-persist
Copy after login
  • axios is used to send HTTP requests;
  • vuex is used for state management;
  • vuex-persist is used to persist state after page refresh.

Project structure:
In the project root directory, we can see the following directory structure:

├── public
│   ├── index.html
│   └── ...
└── src
    ├── api
    │   └── index.js
    ├── components
    │   ├── Player.vue
    │   ├── Playlist.vue
    │   └── ...
    ├── store
    │   ├── index.js
    │   └── ...
    └── App.vue
Copy after login

Among them, the public directory stores static resources, and the src directory The middle is our main code file.

API encapsulation:
First create the api directory and create the index.js file in it. In this file, we will encapsulate the interaction logic with NetEase Cloud API for use in other components.

The sample code is as follows:

import axios from 'axios';

const BASE_URL = 'https://api.music.com';

const api = axios.create({
  baseURL: BASE_URL
});

export const getSongById = async (id) => {
  try {
    const response = await api.get('/song', { params: { id } });
    return response.data;
  } catch (error) {
    console.error(error);
  }
};

export const searchSongs = async (keyword) => {
  try {
    const response = await api.get('/search', { params: { keyword } });
    return response.data;
  } catch (error) {
    console.error(error);
  }
};

// 更多API封装...
Copy after login

In the above code, we use the axios library to create an instance that interacts with the NetEase Cloud API. Through the getSongById and searchSongs methods, we can obtain song information based on the song ID and keywords respectively.

Component Design:
In the components directory, we will create several core components that will make up our music player.

  1. Player.vue:
    This component is responsible for playing and controlling music.
<template>
  <div class="player">
    <!-- 播放/暂停按钮 -->
    <button @click="togglePlayback">{{ isPlaying ? '暂停' : '播放' }}</button>

    <!-- 歌曲封面 -->
    <img :src="currentSong.cover" alt="Song Cover" />

    <!-- 歌曲信息 -->
    <div class="song-info">
      <h2>{{ currentSong.name }}</h2>
      <p>{{ currentSong.artist }}</p>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['currentSong', 'isPlaying'])
  },
  methods: {
    ...mapActions(['togglePlayback'])
  }
};
</script>
Copy after login
  1. Playlist.vue:
    This component is responsible for displaying the current playlist.
<template>
  <ul class="playlist">
    <li v-for="song in playlist" :key="song.id">
      <p>{{ song.name }}</p>
      <p>{{ song.artist }}</p>
    </li>
  </ul>
</template>

<script>
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['playlist'])
  }
};
</script>
Copy after login

These are two basic component examples. In actual projects, you can add more components according to your needs.

Vuex State Management:
In the store directory, we will create a file named index.js, which will be used for storage and management The status of the application.

The sample code is as follows:

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    currentSong: null,
    playlist: [],
    isPlaying: false
  },
  mutations: {
    setCurrentSong(state, song) {
      state.currentSong = song;
    },
    setPlaylist(state, playlist) {
      state.playlist = playlist;
    },
    togglePlayback(state) {
      state.isPlaying = !state.isPlaying;
    }
  },
  plugins: [createPersistedState()]
});
Copy after login

Here, we define a state tree, which includes the currently playing song, playlist and playback status. We can update the status through mutations methods such as setCurrentSong, setPlaylist and togglePlayback.

Application entrance:
Finally, we need to write the application entrance in the main file App.vue.

<template>
  <div id="app">
    <Player />
    <Playlist />
  </div>
</template>

<script>
import Player from './components/Player.vue';
import Playlist from './components/Playlist.vue';

export default {
  components: {
    Player,
    Playlist
  }
};
</script>
Copy after login

In the above code, we introduce the Player and Playlist components into the App.vue file and use them in the template.

Summary:
By using the golden combination of Vue.js and NetEase Cloud API, we successfully built a modern music player. In this example, we learned how to encapsulate API requests, create components, use state management and other basic technologies. Of course, there are many ways this example can be expanded, such as adding a playback progress bar, song switching functions, etc.

Through this project, I hope it can help you better understand the componentization idea of ​​Vue.js and the method of using third-party APIs. At the same time, you are also encouraged to try more functions and innovations in actual projects to build a unique music player.

The complete sample code can be found on GitHub.

Reference link:

  • Vue official documentation: https://vuejs.org/
  • NetEase Cloud Music API documentation: https://github.com/ Binaryify/NeteaseCloudMusicApi

The above is the detailed content of Building a modern music player: the golden combination of Vue and NetEase Cloud API. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template