Detailed explanation of Howler. js Web audio playback ultimate solution

  • 2021-08-06 20:57:35
  • OfStack

Preface

I believe that many people have stepped on many pits when writing audio playback on the mobile terminal, especially when complex audio projects are compatible with various devices, it makes you mad. For example, ios can't play audio from the beginning, and users must operate it. . . .

Accidentally learned that an audio engine compatible with all devices and browsers Howler. js is perfect after using 1

Howler. js is a new JavaScript library for processing audio in Web. This library was originally developed for an HTML5 game engine, but it can also be used for other Web projects. Howler. js Web Audio API based on Google can help you control audio quickly, simply and comprehensively.

Features and compatibility

Howler. js uses Web Audio by default, but it can be automatically converted to HTML 5 Audio on IE. This is very sweet. Both Safari and Chrome on the mobile terminal prohibit the web page from playing sound automatically, which must be triggered by the user's operation, touch, click, etc. Howler. js can be set to automatically capture user actions to activate (unban) sound playback. Howler. js supports many sound formats for compatibility with various browsers. MP3, MPEG, OPUS, OGG, OGA, WAV, AAC, CAF, M4A, MP4, WEBA, WEBM, DOLBY, FLAC. Almost all formats are covered Support 3D games Automatic caching Support fade-in and fade-out effects Lightweight Pure JS No third party dependence Modularization

"For more features, go to Github to see Howler. js"

Usage

It's introduced on the official website, but there's not much discussion here


import {Howl, Howler} from 'howler';

//  Initialization 1 Audio classes 
const sound = new Howl({
 src: ['sound.webm', 'sound.mp3']
});

//  Play audio 
sound.play();

//  Change the Global Audio Sound Size 
Howler.volume(0.5);

//  You just want to change the size of a certain audio. You can modify it during initialization 
const sound = new Howl({
 src: ['sound.webm', 'sound.mp3'],
 volume:0.5
});

Using Howler. js

The most basic, 1 MP3 playback:


var sound = new Howl({
 urls: ['sound.mp3']
}).play();

More playback options:


var sound = new Howl({
 urls: ['sound.mp3', 'sound.ogg', 'sound.wav'],
 autoplay: true,
 loop: true,
 volume: 0.5,
 onend: function() {
  console.log('Finished!');
 }
});

Defining and Playing Audio for a Part 1


var sound = new Howl({
 urls: ['sounds.mp3', 'sounds.ogg'],
 sprite: {
  blast: [0, 1000],
  laser: [2000, 3000],
  winner: [4000, 7500]
 }
});

// shoot the laser!
sound.play('laser');

Summarize

The audio library encapsulated by itself will have some performance and compatibility problems more or less. For example, Howler handles it very well when the audio is played circularly, and there is no feeling of cutting


Related articles: