Vue-music details about the Player components, vue-musicplayer

Source: Internet
Author: User
Tags emit

Vue-music details about the Player components, vue-musicplayer

The examples in this article share with you the specific content of the Player components for your reference. The specific content is as follows:

Mini PLAYER:

1. The Player component will be opened on each page. First, define the global player status in vuex state. js.

Import {playMode} from 'common/js/config. js'; const state = {singer :{}, playing: false, // whether to play fullScreen: false, // whether to play full screen playList: [], // play list sequenceList: [], // unordered playback list mode: playMode. sequence, // playback mode (sequence 0, loop 1, random 2) currentIndex:-1, // current playback index} export default state ----------------------------------------------- // config. jsexport const playMode = {sequence: 0, loop: 1, random: 2}

2. When you enter the player page, you can obtain the playback list data and change the playback status in the music-list.

Dispatch an event to the parent component in the song-list component to pass in the information and index of the current song.

<li @click="selectItem(song,index)" v-for="(song,index) in songs" class="item">------------------------------selectItem(item,index){ this.$emit('select',item,index)},

Distribute events in the music-list component.

<song-list :rank="rank" :songs="songs" @select="selectItem"></song-list> 

3. If multiple states of commit are set in actions

import {playMode} from 'common/js/config.js'export const selectPlay = function({commit,state},{list,index}){ commit(types.SET_SEQUENCE_LIST, list) commit(types.SET_PLAYLIST, list) commit(types.SET_CURRENT_INDEX, index) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true)}

4. Submit the change value using mapActions in the music-list component.

import {mapActions} from 'vuex'methods:{  selectItem(item,index){   this.selectPlay({    list:this.songs,    index   })  },  ...mapActions([   'selectPlay'  ]) },

5. Get the vuex Global Status in palyer and assign values to the corresponding position (the code is complete code, which will be explained later)

<Div class = "player" v-show = "playList. length> 0 "> // <div class =" normal-player "v-show =" fullScreen "> <div class =" background "">  // blur the background image </div> <div class =" top "> <div class =" back" @ click = "back"> <I class = "icon-back"> </I> </div> 

Enable the player status

import {mapGetters,mapMutations} from 'vuex';...mapGetters([  'fullScreen',  'playList',  'currentSong',  'playing',  'currentIndex',])

Note: you cannot directly assign values to the status this. fullScreen = false in the modified vuex. You need to change the value through mutations to define mutation-types and mutations, and then call them using the mapMutations proxy method of vuex.

[types.SET_FULL_SCREEN](state, flag) {  state.fullScreen = flag },import {mapGetters,mapMutations} from 'vuex';methods:{  ...mapMutations({  setFullScreen:"SET_FULL_SCREEN",    }),  back(){  this.setFullScreen(false)  },}

Set the method for clicking the play button

 <i :class="playIcon" @click="togglePlaying"></i>
TogglePlaying () {this. setPlayingState (! This. playing); // change the attributes of the global variable playing}, // watch listens to the playing pause of the actual audio tag of the playing Operation watch: {playing (newPlaying) {let audio = this. $ refs. audio; this. $ nextTick () => {newPlaying? Audio. play (): audio. pause () ;}}, // use the computing attribute to change the corresponding pause icon playIcon () {return this. playing? 'Icon-pause': 'icon-play '},

Set the method of clicking the previous and next buttons for playing. Use mapGetters to get the value of currentIndex (plus one or minus one) and change it to the currentSong status. The Listener switches the playback mode. Determines whether the playback list limit is reset.

Prev () {if (! This. songReady) {return;} let index = this. currentIndex-1; if (index =-1) {// determine the playback list boundary reset index = this. playList. length-1;} this. setCurrentIndex (index); if (! This. playing) {// determine whether to change the playing pause icon this. togglePlaying ();} this. songReady = false ;}, next () {if (! This. songReady) {return;} let index = this. currentIndex + 1; if (index = this. playList. length) {// determine the playback list limit reset index = 0;} this. setCurrentIndex (index); if (! This. playing) {this. togglePlaying ();} this. songReady = false ;},

Listen to the canpaly event of the audio element label. When the song is loaded and the error event occurs, perform a user experience to prevent the user from reporting errors due to quick switch.

Set the songReady flag. If the song is not ready, directly return false when you click the next one.

data(){  return {    songReady:false,  }},ready(){  this.songReady = true;},error(){  this.songReady = true;},

Progress bar

The audio element listens to the timeupdate event to obtain the read/write attribute timestamp of the current playback time. Use formt for formatting time processing (_ pad is the zero-padding function)

Obtain the total audio duration currentSong. duration

<div class="progress-wrapper"> <span class="time time-l">{{ format(currentTime) }}</span> <div class="progress-bar-wrapper">  <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar> </div> <span class="time time-r">{{ format(currentSong.duration) }}</span></div><audio :src="currentSong.url" ref="audio" @canplay="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
UpdateTime (e) {this. currentTime = e.tar get. currentTime; // get the current playback period}, format (interval) {interval = interval | 0; const minute = interval/60 | 0; const second = this. _ pad (interval % 60); return '$ {minute }:: {second}';}, _ pad (num, n = 2) {let len = num. toString (). length; while (len <n) {num = '0' + num; len ++;} return num ;},

Create the penss-bar component to receive the pencent progress parameter and set the progress bar width and the position of the ball. Player component setting computing attribute percent

Percent () {return this. currentTime/this. currentSong. duration // the current duration divided by the total duration },

Progress-bar component

<div class="progress-bar" ref="progressBar" @click="progressClick">  <div class="bar-inner">   <div class="progress" ref="progress"></div>   <div class="progress-btn-wrapper" ref="progressBtn"      @touchstart.prevent="progressTouchStart"      @touchmove.prevent="progressTouchMove"      @touchend="progressTouchEnd"      >    <div class="progress-btn"></div>   </div>  </div> </div>
Const progressBtnWidth = 16 // ball width props: {percent: {type: Number, default: 0 }}, watch: {percent (newPercent) {if (newPercent> = 0 &&! This. touch. initated) {const barWidth = this. $ refs. progressBar. clientWidth-progressBtnWidth; const offsetWidth = newPercent * barWidth; this. $ refs. progress. style. width = '$ {offsetWidth} px'; this. $ refs. progressBtn. style. transform = 'translate3d ($ {offsetWidth} px )'}}}

Set drag

Add the touchstart, touchmove, and touchend event listening methods on the progress bar button progressBtn. Add the prevent to the event to prevent the default browser drag behavior and obtain the dragged information for calculation.

Create a touch object on the instance to maintain the communication sharing status information between different callbacks. In the touchstart event method, set this. touch. initated to true, which indicates the start of the drag operation. Record Start click position e. touches [0]. pageX is saved to the touch object to record the current progress width.

In touchmove, first determine whether the touchstart method is enabled, and calculate the offset length of the Moving position minus the start position. Let deltax = e. touches [0]. pageX-this. touch. startX

You can set the length of the progress bar and the offset length. The maximum length of the parent ssssbar cannot exceed

Call this. _ offset (offsetWidth) to set the progress bar width.

In the touchend event method, set this. touch. initated to false, indicating that the drag ends and the event is distributed to the player component to set the currentTime value of audio to the correct value. The parameter is pencent.

Add a click event in progressbar, call this. _ offset (e. offsetX), and dispatch the event

 created(){  this.touch = {}; },methods:{ progressTouchStart(e){  this.touch.initiated = true;  this.touch.startX = e.touches[0].pageX;  this.touch.left = this.$refs.progress.clientWidth; }, progressTouchMove(e){  if(!this.touch.initiated){   return;  }  let deltaX = e.touches[0].pageX - this.touch.startX;  let offsetWidth = Math.min(this.$refs.progressBar.clientWidth - progressBtnWidth,Math.max(0,this.touch.left + deltaX));  this._offset(offsetWidth); }, progressTouchEnd(e){  this.touch.initiated = false;  this._triggerPercent(); }, progressClick(e){  const rect = this.$refs.progressBar.getBoundingClientRect();  const offsetWidth = e.pageX - rect.left;  this._offset(offsetWidth);  // this._offset(e.offsetX);  this._triggerPercent(); }, _offset(offsetWidth){  this.$refs.progress.style.width = `${offsetWidth}px`;  this.$refs.progressBtn.style[transform] = `translate3d(${offsetWidth}px,0,0)`; }, _triggerPercent(){  const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth;  const percent = this.$refs.progress.clientWidth / barWidth;  this.$emit("percentChange",percent) }},

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.