How to Use Howler.js in Vue.js

This article provides a quick, step-by-step guide on how to integrate and use Howler.js, a robust audio library, within a Vue.js application. You will learn how to install the library, set up a basic audio player in a Vue 3 component using the Composition API, and properly manage the audio lifecycle to prevent memory leaks.

Step 1: Install Howler.js

First, you need to install the howler package in your Vue project. Open your terminal and run one of the following commands depending on your package manager:

npm install howler
# or
yarn add howler
# or
pnpm add howler

Step 2: Create the Audio Component

Create a new Vue component (e.g., AudioPlayer.vue). You will import the Howl class from howler and instantiate it inside your setup script.

Here is a complete, minimal example using Vue 3 <script setup> syntax:

<template>
  <div class="audio-player">
    <h3>Audio Player</h3>
    <button @click="playAudio" :disabled="isPlaying">Play</button>
    <button @click="pauseAudio" :disabled="!isPlaying">Pause</button>
    <button @click="stopAudio">Stop</button>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { Howl } from 'howler';

// Track the playback state
const isPlaying = ref(false);

// Initialize the Howl instance
const sound = new Howl({
  src: ['https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'],
  html5: true, // Use HTML5 Audio to support large files/streaming
  onplay: () => {
    isPlaying.value = true;
  },
  onpause: () => {
    isPlaying.value = false;
  },
  onstop: () => {
    isPlaying.value = false;
  },
  onend: () => {
    isPlaying.value = false;
  }
});

// Control methods
const playAudio = () => {
  sound.play();
};

const pauseAudio = () => {
  sound.pause();
};

const stopAudio = () => {
  sound.stop();
};

// Clean up audio resources when the component is destroyed
onUnmounted(() => {
  sound.unload();
});
</script>

<style scoped>
.audio-player {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  max-width: 300px;
}
button {
  margin-right: 10px;
  padding: 8px 12px;
  cursor: pointer;
}
button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>

Key Integration Tips