Example code of vue + element ui to realize player function

Example code of vue + element ui to realize player function

The display without the effect picture is just empty words.

insert image description here

1. Progress bar implementation based on audio and combined with elementUI
2. Realize the basic functions of the player, including play/pause, fast forward, mute, adjust volume, download, etc.

HTML code, key parts are commented

<div class="right di main-wrap" v-loading="audio.waiting">
   <!-- The ref attribute here can be easily used to obtain the DOM element in the Vue component through this.$refs.audio-->
   <audio ref="audio" class="dn"
   :src="url" :preload="audio.preload"
   @play="onPlay"
   @error="onError"
   @waiting="onWaiting"
   @pause="onPause"
   @timeupdate="onTimeupdate"
   @loadedmetadata="onLoadedmetadata"
   ></audio>

   <div class="w-full">
     <div class="flex items-center w-10/12 mx-auto">
       <!-- Current time -->
       <el-tag type="info">{{ audio.currentTime | formatSecond}}</el-tag>

       <!-- Scrollbar -->
       <el-slider v-show="!controlList.noProcess" v-model="sliderTime" :format-tooltip="formatProcessToolTip" @change="changeCurrentTime" class="slider_time"></el-slider>
       <!-- Total duration-->
       <el-tag type="info">{{ audio.maxTime | formatSecond }}</el-tag>
     </div>
     <div class="mt-3 flex items-center w-1/2 mx-auto justify-around">
       <!-- Play/Pause -->
       <el-button type="text" @click="startPlayOrPause">{{audio.playing | transPlayPause}}</el-button>
       <!-- Fast forward -->
       <el-button v-show="!controlList.noSpeed" type="text" @click="changeSpeed">{{audio.speed | transSpeed}}</el-button>
       <!-- Mute -->
       <el-button v-show="!controlList.noMuted" type="text" @click="startMutedOrNot">{{audio.muted | transMutedOrNot}}</el-button>
       <!-- Volume -->
       <div class="flex items-center">
         <span class="mr-2 text-sm">Volume</span>
         <el-slider v-show="!controlList.noVolume" v-model="volume" :format-tooltip="formatVolumeToolTip" @change="changeVolume" class="slider_voice"></el-slider>
       </div>

       <!-- Download -->
       <a :href="url" rel="external nofollow" v-show="!controlList.noDownload" target="_blank" class="download text-sm" download>Download</a>
     </div>
   </div>
 </div>

js code

<script>
  // Convert integer to hour:minute:second format 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 {
    name: 'voicetotext',
    props: {
      theSpeeds:
        type: Array,
        default () {
          return [1, 1.5, 2]
        }
      },
      theControlList: {
        type: String,
        default: ''
      }
    },
    data(){
      return {
        url: 'https://wdd.js.org/element-audio/static/falling-star.mp3',
        audio:
          currentTime: 0,
          maxTime: 0,
          playing: false,
          muted: false,
          speed: 1,
          waiting: true,
          preload: 'auto'
        },

        sliderTime: 0,
        volume: 100,
        speeds: this.theSpeeds,

        controlList: {
          // Do not display download noDownload: false,
          // Do not display the mute noMuted: false,
          // Do not display the volume bar noVolume: false,
          // Do not display the progress bar noProcess: false,
          // Only one can be played onlyOnePlaying: false,
          // Do not fast forward button noSpeed: false
        }
      }
    },
    methods:{
      setControlList () {
        let controlList = this.theControlList.split(' ')
        controlList.forEach((item) => {
          if(this.controlList[item] !== undefined){
            this.controlList[item] = true
          }
        })
      },
      changeSpeed() {
        let index = this.speeds.indexOf(this.audio.speed) + 1
        this.audio.speed = this.speeds[index % this.speeds.length]
        this.$refs.audio.playbackRate = this.audio.speed
      },
      startMutedOrNot() {
        this.$refs.audio.muted = !this.$refs.audio.muted
        this.audio.muted = this.$refs.audio.muted
      },
      // Volume bar toolTip
      formatVolumeToolTip(index) {
        return 'Volume bar: ' + index
      },
      //Progress bar toolTip
      formatProcessToolTip(index = 0) {
        index = parseInt(this.audio.maxTime / 100 * index)
        return 'Progress bar: ' + realFormatSecond(index)
      },
      // Volume changechangeVolume(index = 0) {
        this.$refs.audio.volume = index / 100
        this.volume = index
      },
      // Play jump changeCurrentTime(index) {
        this.pausePlay()
        this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime)
      },
      startPlayOrPause() {
        return this.audio.playing ? this.pausePlay() : this.startPlay()
      },
      // Start playing startPlay() {
        this.$refs.audio.play()
      },
      // Pause pausePlay() {
        this.$refs.audio.pause()
      },
      // When the audio is paused onPause () {
        this.audio.playing = false
      },
      // When an error occurs, the loading state appears onError () {
        this.audio.waiting = true
      },
      // When the audio starts waiting onWaiting (res) {
        console.log(res)
      },
      // When the audio starts playing 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');

        [...audios].forEach((item) => {
          if(item !== target){
            item.pause()
          }
        })
      },
      // The timeupdate event is called approximately once per second to update the current playback time of the audio stream onTimeupdate(res) {
        // console.log('timeupdate')
        // console.log(res)
        this.audio.currentTime = res.target.currentTime
        this.sliderTime = parseInt(this.audio.currentTime / this.audio.maxTime * 100)
      },
      //When the voice stream metadata is loaded, the callback function of this event will be triggered //The voice metadata mainly includes data such as the length of the voice onLoadedmetadata(res) {
        this.audio.waiting = false
        this.audio.maxTime = parseInt(res.target.duration)
      }
    },
    filters:
      formatSecond(second = 0) {
        return realFormatSecond(second)
      },
      transPlayPause(value) {
        return value ? 'Pause' : 'Play'
      },
      transMutedOrNot(value) {
        return value ? 'Play' : 'Mute'
      },
      transSpeed(value) {
        return 'Fast forward: x' + value
      }
    },
    created() {
      this.setControlList()
    }
  }
</script>

The CSS code uses SCSS

<style scoped lang="scss">
  .right{
     width: 100%;
     padding: 10px 15px;
     display: inline-block;
     .slider {
       display: inline-block;
       position: relative;
       top: 14px;
       margin-left: 15px;
     }
     .slider_time{
       width: 550px;
       margin: 0 10px;
     }
     .slider_voice{
       width: 80px;
     }
     .download {
       color: #409EFF;
       margin-left: 15px;
     }

     .dn{
       display: none;
     }
   }

</style>

A beautiful test music is also included
https://wdd.js.org/element-audio/static/falling-star.mp3

This is the end of this article about vue + element ui to realize the player function. For more relevant vue element ui player content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue-Video-Player operation for Vue
  • Detailed configuration of vue-video-player video player
  • vue-dplayer video player example code
  • Vue implements the method and steps of custom H5 video player
  • Implementing music player function based on vue-element component
  • Method of customizing player based on vue-video-player
  • An example of implementing a music player in a vue page
  • Detailed explanation of the Player component in vue-music
  • Detailed explanation of the configuration and usage examples of the vue music player plugin vue-aplayer
  • Vue.js implements music player

<<:  MySql inserts data successfully but reports [Err] 1055 error solution

>>:  Detailed explanation of the basic use of centos7 firewall in linux

Recommend

Docker Gitlab+Jenkins+Harbor builds a persistent platform operation

CI/CD Overview CI workflow design Git code versio...

The difference and execution method of select count() and select count(1)

Count(*) or Count(1) or Count([column]) are perha...

Native js implements custom scroll bar component

This article example shares the specific code of ...

Detailed explanation of the basic use of centos7 firewall in linux

1. Basic use of firewalld start up: systemctl sta...

jQuery implements ad display and hide animation

We often see ads appear after a few seconds and t...

Mysql anonymous login cannot create a database problem solution

Frequently asked questions Access denied for user...

The difference between key and index in MySQL

Let's look at the code first: ALTER TABLE rep...

The latest graphic tutorial of mysql 8.0.16 winx64 installation under win10

In order to download this database, it takes a lo...

MySQL 5.7.16 ZIP package installation and configuration tutorial

This article shares the installation and configur...

MySQL DeadLock troubleshooting full process record

【author】 Liu Bo: Senior Database Manager at Ctrip...

The problem of form elements and prompt text not being aligned

Recent projects involve the creation of a lot of ...

Eclipse configures Tomcat and Tomcat has invalid port solution

Table of contents 1. Eclipse configures Tomcat 2....

Simplify complex website navigation

<br />Navigation design is one of the main t...

What should I do if I can't view the source file of a web page?

Q: Whether using Outlook or IE, when you right-cl...

Example of how to implement local fuzzy search function in front-end JavaScript

Table of contents 1. Project Prospects 2. Knowled...