Vue + elementui: how to make an audio component

Time:2020-9-20

objective

  • The purpose of this project is to teach you how to implement a simple music player (it’s not hard)
  • This project is not an element player that can be used in production environment, so it does not consider too many compatibility issues
  • This project is not an audio plug-in of elementui, but a tutorial, but you can implement it by yourself
  • This project is only for learning audio related events and API

The audio files for this project are located atstatic/falling-star.mp3, the song is called: star fall live AI Ge, Li Jialong

  • View online demo: https://wangduanduan.github.i…
  • Project address: https://github.com/wangduandu…

function

cd element-aduio && yarn && yarn run dev

file

1. Introduction

1.1 related technologies

  • Vue
  • Vue-cli
  • ElementUI
  • I used NPM and cnpm’s source before, but after using yarn, I found that it was faster and more functional than cnpm, so I didn’t hesitate to choose yarn
  • Audio related APIs and events

1.2 what will you learn from this tutorial?

  • Vue single file component development knowledge
  • Element UI basic usage
  • Audio native API and audio related events
  • Basic principles of audio player
  • Audio playback pause control
  • Audio display time
  • Audio progress bar control and jump
  • Audio volume control
  • Audio playback speed control
  • Audio mute control
  • Audio download control
  • Personalized configuration and exclusive play
  • A little bit of ES6 syntax

1.3 pre school preparation

Basically no preparation is needed, but it would be better if you could take a look at the API and events related to aduio first

  • Audio: if you want to peel my heart off layer by layer
  • Using HTML5 audio and video

1.4 online demo

No online demo tutorial is playing rogue

  • View online demon
  • Project address

2 start coding

2.1 project initialization

➜  test vue init webpack element-audio

  A newer version of vue-cli is available.

  latest:    2.9.2
  installed: 2.9.1

? Project name element-audio
? Project description A Vue.js project
? Author wangdd 
? Vue build standalone
? Install vue-router? No
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm

➜  test cd element-audio 
➜  element-audio npm run dev

Browser openhttp://localhost:8080/, see the following interface, indicating that the project initialization is successful

Picture 1

2.2 install element UI and insert audio tag

2.2.1 Install elementui

yarn add element-ui // or npm i element-ui -S

2.2.2src/main.jsIntroducing element UI in

// filename: src/main.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import App from './App'
import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false

Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '',
  components: { App }
})

2.2.3 createsrc/components/VueAudio.vue

// filename: src/components/VueAudio.vue

  
    
  



export default {
  data () {
    return {}
  }
}

2.2.4 modificationsrc/App.vueAnd introduceVueAudio.vueassembly

// filename: src/App.vue

  
    
  



import VueAudio from './components/VueAudio'

export default {
  name: 'app',
  components: {
    VueAudio
  },
  data () {
    return {}
  }
}

Open: http://localhost : 8080 /, you should be able to see the following effect, indicating that the introduction is successful. You can click the play button to see if the audio can be played
Figure 2

2.3 audio playback pause control

We need to use a button to control the playback and pause of audio. Here we call two APIs of audio and two events

  • audio.play()
  • audio.pause()
  • Play event
  • Pause event

modifysrc/components/VueAudio.vue

// filename: src/components/VueAudio.vue

  
    
    

    
    
      {{audio.playing | transPlayPause}}
    
  



export default {
  data () {
    return {
      audio: {
        //This field is an attribute of whether the audio is playing or not
        playing: false
      }
    }
  },
  methods: {
    //Control audio playback and pause
    startPlayOrPause () {
      return this.audio.playing ? this.pause() : this.play()
    },
    //Play audio
    play () {
      this.$refs.audio.play()
    },
    //Pause audio
    pause () {
      this.$refs.audio.pause()
    },
    //When the audio is playing
    onPlay () {
      this.audio.playing = true
    },
    //When audio pauses
    onPause () {
      this.audio.playing = false
    }
  },
  filters: {
    //Use component filters to dynamically change the display of buttons
    transPlayPause(value) {
      Return value?'pause ':' play '
    }
  }
}

Figure 3 audio playback and pause

2.4 audio display time

The time display of audio mainly includes two parts: the total duration of audio and the current playing time. It can be obtained from two events

  • loadedmetadata: the metadata representing the audio has been loaded, and the total audio duration can be obtained from it
  • timeupdate: if the current playback position is changed as part of normal playback, or changed in a particularly interesting way, such as discontinuously, the current playback time of audio can be obtained from the event,This event will be triggered continuously during playback

Key point code: integer format: Min: sec

function realFormatSecond(second) {
  var secondType = typeof second

  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second)

    var hours = Math.floor(second / 3600)
    second = second - hours * 3600
    var mimute = Math.floor(second / 60)
    second = second - mimute * 60

    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
  } else {
    return '0:00:00'
  }
}

Key point code: handling of two events

//When the timeupdate event is about once per second, it is used to update the current playback time of the audio stream
onTimeupdate(res) {
      console.log('timeupdate')
      console.log(res)
      this.audio.currentTime = res.target.currentTime
    },
//When the loading of voice stream metadata is completed, the callback function of the event will be triggered
//Voice metadata is mainly data such as the length of voice
onLoadedmetadata(res) {
  console.log('loadedmetadata')
  console.log(res)
  this.audio.maxTime = parseInt(res.target.duration)
}

Complete code

{{audio.playing | transPlayPause}}

      {{ audio.currentTime | formatSecond}}

      {{ audio.maxTime | formatSecond}}
    
  




//Convert an integer to the format of hour: minute: second
function realFormatSecond(second) {
  var secondType = typeof second

  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second)

    var hours = Math.floor(second / 3600)
    second = second - hours * 3600
    var mimute = Math.floor(second / 60)
    second = second - mimute * 60

    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
  } else {
    return '0:00:00'
  }
}

export default {
  data () {
    return {
      audio: {
        //This field is an attribute of whether the audio is playing or not
        playing: false,
        //Current audio playback duration
        currentTime: 0,
        //Maximum audio playback time
        maxTime: 0
      }
    }
  },
  methods: {
    //Control audio playback and pause
    startPlayOrPause () {
      return this.audio.playing ? this.pause() : this.play()
    },
    //Play audio
    play () {
      this.$refs.audio.play()
    },
    //Pause audio
    pause () {
      this.$refs.audio.pause()
    },
    //When the audio is playing
    onPlay () {
      this.audio.playing = true
    },
    //When audio pauses
    onPause () {
      this.audio.playing = false
    },
    //When the timeupdate event is about once per second, it is used to update the current playback time of the audio stream
    onTimeupdate(res) {
      console.log('timeupdate')
      console.log(res)
      this.audio.currentTime = res.target.currentTime
    },
    //When the loading of voice stream metadata is completed, the callback function of the event will be triggered
    //Voice metadata is mainly data such as the length of voice
    onLoadedmetadata(res) {
      console.log('loadedmetadata')
      console.log(res)
      this.audio.maxTime = parseInt(res.target.duration)
    }
  },
  filters: {
    //Use component filters to dynamically change the display of buttons
    transPlayPause(value) {
      Return value?'pause ':' play '
    },
    //Convert integers into hours, minutes and seconds
    formatSecond(second = 0) {
      return realFormatSecond(second)
    }
  }
}

Open the browser and you can see that the current time is also changing when the audio is playing.
Figure 4

2.5 audio progress bar control

The progress bar mainly has two controls. The principle of changing the progress is: changeaudio.currentTimeProperty value

  • After the audio is played, the current time changes, and the progress bar will change accordingly
  • Drag the progress bar to change the current time of the audio
//Progress bar UI


//Drag the progress bar to change the current time. Index is the parameter of the callback function when the progress bar changes. It is between 0 and 100, which needs to be converted into the actual time
changeCurrentTime(index) {
  this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime)
},
//When the current audio time changes, the progress bar should also be changed
onTimeupdate(res) {
  console.log('timeupdate')
  console.log(res)
  this.audio.currentTime = res.target.currentTime
  this.sliderTime = parseInt(this.audio.currentTime / this.audio.maxTime * 100)
},

//Progress bar formatting tooltip
formatProcessToolTip(index = 0) {
  index = parseInt(this.audio.maxTime / 100 * index)
  Return 'progress bar:' + realformatsecond (index)
},

2.6 audio volume control

Audio volume control and progress control is similar, but also by dragging the slider, to modifyaduio.volumeProperty value, no longer wordy here

2.7 audio playback speed control

Audio volume control and progress control is similar, but also click the button to modifyaduio.playbackRateAttribute value. This attribute represents the volume. The value range is 0 – 1. When you use the slider bar, you need to convert the value

2.8 audio mute control

Mute control is to click the button to modifyaduio.mutedProperty, which has two values: true (mute) and false (unmutable). Note that the audio progress bar will continue to move forward when mute.

2.9 audio download control

Audio download is a link, remember to adddownloadOtherwise, the browser will open the audio in the new tab instead of downloading it

download

2.10 personalized configuration

There are a lot of personalized audio configuration. You can expand it by yourself. You can transfer the response value through the parent component to achieve personalized settings.

controlList: {
  //Do not show Downloads
  noDownload: false,
  //Do not show mute
  noMuted: false,
  //Do not show volume bar
  noVolume: false,
  //Do not show progress bar
  noProcess: false,
  //Only one can be played
  onlyOnePlaying: false,
  //Don't fast forward button
  noSpeed: false
}

setControlList () {
    let controlList = this.theControlList.split(' ')
    controlList.forEach((item) => {
      if(this.controlList[item] !== undefined){
        this.controlList[item] = true
      }
    })
},

For example, the parent component

import VueAudio from './components/VueAudio'

export default {
  name: 'app',
  components: {
    VueAudio
  },
  data () {
    return {
      audios: [
        {
          url: 'http://devtest.qiniudn.com/secret base~.mp3',
          controlList: 'onlyOnePlaying'
        },
        {
          url: ' http://devtest.qiniudn.com/ Come back! Snow moon flower. MP3 ',
          controlList: 'noDownload noMuted onlyOnePlaying'
        },{
          url: ' http://devtest.qiniudn.com/ Youth! MP3 ',
          controlList: 'noDownload noVolume noMuted onlyOnePlaying'
        },{
          url: 'http://devtest.qiniudn.com/Preparation.mp3',
          controlList: 'noDownload noSpeed onlyOnePlaying'
        }
      ]
    }
  }
}

2.11 a little bit of ES6 syntax

Most of the time, we want to play one audio on the page while the other audio can pause.
[...audios]You can convert an array of classes into an array, which I usually use.

onPlay (res) {
    console.log(res)
    this.audio.playing = true
    this.audio.loading = false
    
    if(!this.controlList.onlyOnePlaying){
      return 
    }
    
    let target = res.target
    
    let audios = document.getElementsByTagName('audio');
    //If exclusivity is set, all other audio will be suspended when the current audio is playing
    [...audios].forEach((item) => {
      if(item !== target){
        item.pause()
      }
    })
},

thank

  • If you need a small Vue music player, you can try Vue aplayer. The player supports not only Vue components, but also non Vue ones. You can see their demo

Recommended Today

1. Rxswift creates observable sequences

Empty() method initialization //An observable empty content is created let ob = Observable.empty() //First, write a simple subscription method ob.subscribe {print “} The just() method passes in the default value initialization //There is no need to give a generic, it will be automatically pushed out according to just let ob = Observable.just (initialization default) The […]