Search code examples
javascripthtml5-audiohowler.js

Structure Howler.js script for playback just like this SoundManager2 example code?


In this question you can find SoundManager2 and Howler.js code examples for audio playback.

I basically use the SoundManager2 script from that page - with a few modifications as shown in the code snippet below.

In my HTML5 browser app I could use this script to simply play a sound by calling the sound id("Song1") and the function("playAudio" for example).

My question:
How can I structure a Howler.js script to get the same functionality
→ play a sound by calling the sound id and the correct function?

Howler.js Documentation

    <!DOCTYPE html>
    <script type="text/javascript" src="api/soundmanager2.js"></script>
    <script>
        soundManager.setup({
    	url: 'api/',
    	onready: function() {

    soundManager.createSound({
        id: 'Song1',
    		url: 'audio/Song1.ogg'
        });
      },
    });
    function playAudio(snd) {
        soundManager.play(snd);
    }
    function stopAudio(snd) {
        soundManager.stop(snd);
    }
    </script>


Solution

  • Howler.js is meant to be a simple API, so it doesn't have this feature built-in, but it would be easy enough to just create a map with an object:

    var Song1 = new Howl({
      src: 'audio/Song1.ogg'
    });
    var Song2 = new Howl({
      src: 'audio/Song2.ogg'
    });
    
    var sounds = {
      Song1: Song1,
      Song2: Song2,
    };
    
    function playAudio(snd) {
      sounds[snd].play();
    }
    
    function stopAudio(snd) {
      sounds[snd].stop();
    }