Although the whole online Vue copy ele. me, XX music project a lot, but I still cheeky come, after all, I also slightly unconventional, PC side based, mobile side as auxiliary to build the Web music player, so say the big guys love, after all, I just came back from Korea this player!!

Imitate QQ Music web version interface, using Flexbox and Position layout; Although mmPlayer is responsive, it is mainly used for PC, and only suitable for mobile (without lyrics display). Only do mainstream browser compatibility (say goodbye to IE and special optimization, think about the previous project to compatible with IE7, are tears!!)

API: an open source API for netease Cloud Music NodeJS version.

Vue-mmplayer source address

Online demo address server fragile, little brother little sister to be gentle oh (the best IS PC browsing oh)

How to install and use

mmPlayer

git clonehttps://github.com/maomao1996/Vue-mmPlayer.git/download/mmPlayercdNPM install // Install depends on NPM run dev // The server runs NPM run build // package the projectCopy the code

Background server

cdMmPlayer /server // Go to the background server directory NPM install // Install dependent Node app.js // Run the server to visit http://localhost:3000Copy the code

If you cannot obtain music after running mmPlayer, check whether the background server is started

The URL of music in the API directory must be the same as that of the background server

Technology stack

  • Vue-cli (Vue Scaffolding Tool)
  • Vue (Core Framework)
  • Vue-router (Page Routing)
  • Vuex (State Management)
  • ES 6/7 (next generation standard for JavaScript language)
  • Less (CSS preprocessor)
  • Axios (Network Request)
  • FastClick (solve 300ms click delay on mobile)

Interface to appreciate

The PC interface feels ok, but the mobile interface always feels strange, but the aesthetic is limited, so I went to the high imitation netease Cloud React version (if there is a nice interface, welcome to exchange!)

PC

There is

list

search

My song list

I have heard of

Song reviews

The mobile terminal

function

Player, shortcut key operation, lyrics scrolling, Playing, ranking, playlist details, search, play history, view comments, and synchronize netease Cloud playlist

Player (Core)

In fact, the player function is just like that, call HTML5 audio methods, attributes and events, all kinds of online articles are also introduced rotten, but to cheat praise to have sincerity

I implemented these functions: previous track, next track, pause, play, single loop, list loop, random play, sequence play, progress bar, volume control

Before introducing these functions, I will clarify my ideas. Here is a small demo. After all, there is no code

<! DOCTYPE html> <html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Audio</title>
	<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
	<div id="Audio">
		<audio ref="mmAudio" :src="src" controls></audio>
		<button @click="prev"< p style = "max-width: 100%; clear: both; min-height: 1em"play"</button> < button@click ="next"</button> </div> <script> const vm = new Vue({el:'#Audio',
			data: {
				list: [
					'https://music.163.com/song/media/outer/url?id=450424527.mp3'.'https://music.163.com/song/media/outer/url?id=557581284.mp3'.'https://music.163.com/song/media/outer/url?id=452986458.mp3'],// Array of songs index: 0,// Current songs subscript}, computed: {src() {
					returnThis.list [this.index]}}, methods: {prev() {// Last songlet index = this.index - 1;
					if (index < 0) {
						index = this.list.length - 1
					}
					this.index = index;
					this.$nextTick(() => this.$refs.mmAudio.play())
				},
				play() {// Pause/play this.$nextTick(() => this.$refs.mmAudio.paused ? this.$refs.mmAudio.play() : this.$refs.mmAudio.pause())
				},
				next() {// Next songlet index = this.index + 1;
					if (index === this.list.length) {
						index = 0
					}
					this.index = index;
					this.$nextTick(() => this.$refs.mmAudio.play())
				}
			}
		})
	</script>
</body>
</html>
Copy the code

The logic of this code is very simple: we add a computed dynamically generated song SRC, and when pause/play is clicked, the play method is called to modify the play state. When you click on the previous or the next song, the index of the current song is modified, then computed modification SRC is triggered and the play method is called to play the music

After watching this little demo, all of these functions are easy to understand

Previous/Next: Change the index of the current song played, then computed changes SRC is triggered, and then the play method is called to play the music

Pause/Play: Determine whether the Audio is paused by the paused property of Audio. If true, play is called to play the music, and if false, Paused is called

Single loop: Call Audio’s ended event to reset the currentTime property to 0 after the current song ends

List loop: Calls Audio’s ended event, calling the next method in its callback

Shuffle: Shuffle an array of songs using an array of original songs

Sequence playback: Call Audio’s ended event to determine whether the subscript of the current song is equal to the length of the song array -1. If so, the next song method will not be called

Progress bar/Volume control: Drag and click the progress component encapsulated by yourself to modify the corresponding playback progress currentTime and volume. Note: In the progress event binding, only mouseDown and touchStart events are bound to the corresponding DOM node. Other mouse movements such as mousemove and TouchMove, MouseUp and TouchEnd are all bound to the DOM as documents, otherwise there will be various issues with the chain. For example, the drag will be interrupted if the focus is not on the corresponding DOM

Shortcut key operation

Ctrl + Left

Pause playback with Ctrl + Space

Next Ctrl + Right

Switch the playback mode by Ctrl + O

Ctrl + Up for volume

Volume Down Ctrl + Down

The lyrics scroll

Lyrics scroll principle: Match the time of the JSON data of the lyrics based on the current music playback time, audio. CurrentTime. Then the matched lyrics are displayed in the center and highlighted

First to a song lyrics JSON charming jade photo to you little brother, miss sisters to solve the greedy

{
lyric: [00:00.00] [00:00.00] [00:00.00] [00:00.00] [00:04.60] willen [00:05.10] [00:55.37] Grandma's words [00:59.01] Kind smile with me grow up [01:02.75] every time the garden full of osmanthus [01:06.50] fragrance is love care [01:10.30] Grandma's words remember [01:14.01] Don't forget to go home injured child [01:17.66] the sun is setting the years are turning white
}
Copy the code

Since Audio. CurrentTime is in seconds and the JSON format of the lyrics is sauce [00:00.00], we need to make the lyrics JSON makeup first

// This is the makeup process, I don't have to say the specific process, after all, I am cheeky to dig gold to deceive the cautious heartfunction parseLyric(lrc) {
    let lyrics = lrc.split("\n");
    let lrcObj = [];
    for (let i = 0; i < lyrics.length; i++) {
        let lyric = decodeURIComponent(lyrics[i]);
        let timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
        let timeRegExpArr = lyric.match(timeReg);
        if(! timeRegExpArr)continue;
        let clause = lyric.replace(timeReg, ' ');
        for (let k = 0, h = timeRegExpArr.length; k < h; k++) {
            let t = timeRegExpArr[k];
            let min = Number(String(t.match(/\[\d*/i)).slice(1)),
                sec = Number(String(t.match(/\:\d*/i)).slice(1));
            let time = min * 60 + sec;
            if(clause ! = =' ') {
                lrcObj.push({time: time, text: clause})
            }
        }
    }
    return lrcObj;
}
Copy the code

I compare vegetables, Mars text (re) all rely on the search engine, this is the original address of the lyrics re, but I modified it slightly

When that’s all right just center the time and highlight the current lyrics! At present, I find the first time that is larger than the current playing time by comparing the size of the for loop, but I always feel that this is not elegant, but I can’t think of any other way, I hope to know the elegant method of the little brother, little sister to guide the puzzle

There is

Display and manage the current playlist, you can clear the current player list, delete the top songs, modify the song playing state

list

Call the corresponding API interface to obtain the ranking list of netease Cloud music (currently there is no lazy loading of pictures)

Song list details

Pass in the playlist ID and call the corresponding API interface to obtain all songs under the current playlist. Since it is to obtain all songs, there will be some lag when sliding on the mobile terminal, and Better Scroll (a plug-in that focuses on solving the needs of various scrolling scenes on the mobile terminal) will be added in the later stage.

search

At present, it only realizes the search of songs, and will improve the search of album/singer/song list/user in the future. Obtain the search data through the search keyword request API and display song paging: Call the Scroll event, scroll to the bottom to download the next page, currently 50 songs per page, and when all data requests are completed, it will prompt: No more songs!

In the copyright dispute between netease Cloud Music and QQ Music last time, all the singles of Jay Chou were GG, and THEN I first requested the URL of the current song in the event of playback. If there is no URL, it will prompt: the current song cannot be played; If you don’t do this, it will be bad if you are accused again. After all, the user is the boss

Play the history

PS: at first I played through the play event, the result whether you canplay or not will be added to the playback history, then was teased, finally various studies found that canplay is more elegant

To view comments

This is one of the highlights of Duan Ziyun music. It must be added that the API interface corresponding to the id of the current playing music is called to display the hot comments and the latest comments respectively. When doing this, the interface is simply trivial, but the comment time is simply depressing, including:

Just/XX minutes ago/XX:XX/XX/XX/XX/XX/XX

Probably spent more than half an hour just KO off, but do not know why always feel I write so not elegant, hope to know elegant method of little brother, little sister to point out the confusion

Synchronize netease Cloud Playlist

First, go to netease Cloud Music to obtain its UID, then call the corresponding API interface to obtain the user’s playlist, and then pass in the playlist ID to obtain the playlist details.

If the playList array returned by the UID is 0, the user whose UID is ${UID} is not queried

After successful login, call localStorage to store the current UID. The next login will read the UID of the localStorage

Clear localStorage when you log out to prevent you from logging in again

subsequent

  1. Code increases reuse
  2. Optimized mobile interface and experience, such as Better Scroll, lazy image loading
  3. Album/artist/playlist/user search
  4. Refactoring the backend service with KOA
  5. Improve the desktop experience (after all, it’s too simple to watch)
  6. . (Not enough brain capacity to think of these for the time being)

Thank you

HTML Audio/video DOM Reference manual

Netease Cloud Music NodeJS API

Vue. Js upgrade pit tips

Lodash (JavaScript Utility Library)

other

For my personal training project, I was bored for a while. Then I found an open source music API — netease Cloud Music NodeJS API — while browsing Gayhub. Finally, I sorted out my development ideas while looking for a nice interface

Once there was a period of time when many people asked me what UI framework I used, so I would also mention that the basic UI of the project is a combination of the project and the major UI framework code style slowly knocked, and then recommend a Vue course — VUe.js Music App advanced practical course

React mobile terminal version (high imitation netease cloud music I feel this high imitation has no problem

Finally, let’s get to the point, welcome to give me a “Star” “Fork” (address here vue-mmPlayer source address), after all, it is the first time to post a fake like (smile), little brother, miss sisters give some encouragement.

If you have any questions, please reply in this article or raise them directly in Issues, or if you find a problem and have a good solution, welcome PR