[Vue.js] Toggle (Play/Pause) Audio Sound on Click Event of DOM Element


Toggle (play/pause) audio sound if uers click on DOM Element in Vue.js/JavaScript.

Demo

The key points of the following source code:
  • Use v-on directive to attach event listener of button onClick event.
  • Use ref attribute to register a reference to audio element. We will later access the audio element by the unique reference name audioElm in the event listener.
  • If users click on the button, check the paused property of the audio element. If it's paused, call play() method of the audio element to play the sound. Otherwise call pause() method to stop playing.
index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Vue.js Toggle Audio Sound Onclick Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="app">
  <button v-on:click="play" type="button">Click Me to Toggle Sound</button>
  <audio ref="audioElm" src="../../javascript/play-toggle-sound/Wat_Metta_Buddha_Qualities.mp3"></audio>
</div>

<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
'use strict';

var app = new Vue({
  el: '#app',
  methods: {
    play: function(event) {
      var a = this.$refs.audioElm;
      if (a.paused) {
        a.play();
      } else {
        a.pause();
      }
    }
  }
})

Tested on:
  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.1.10.

References:

[1]
[2]Event Handling — Vue.js
[3]
[4][Vue.js] Play Audio Sound on Click Event of DOM Element