Project Icon

howler.js

跨平台 Web 音频库 支持多种格式与控制

howler.js 是一个轻量级 Web 音频库,统一了音频处理接口。优先使用 Web Audio API,兼容 HTML5 Audio。支持多种音频格式,提供自动缓存、音量调节、3D 音效等功能。无需依赖其他库,压缩后仅 7KB。适用于游戏、音乐播放器等需要复杂音频控制的 Web 应用,简化了跨平台 JavaScript 音频开发。

howler.js

Description

howler.js is an audio library for the modern web. It defaults to Web Audio API and falls back to HTML5 Audio. This makes working with audio in JavaScript easy and reliable across all platforms.

Additional information, live demos and a user showcase are available at howlerjs.com.

Follow on Twitter for howler.js and development-related discussion: @GoldFireStudios.

Features

  • Single API for all audio needs
  • Defaults to Web Audio API and falls back to HTML5 Audio
  • Handles edge cases and bugs across environments
  • Supports all codecs for full cross-browser support
  • Automatic caching for improved performance
  • Control sounds individually, in groups or globally
  • Playback of multiple sounds at once
  • Easy sound sprite definition and playback
  • Full control for fading, rate, seek, volume, etc.
  • Easily add 3D spatial sound or stereo panning
  • Modular - use what you want and easy to extend
  • No outside dependencies, just pure JavaScript
  • As light as 7kb gzipped

Browser Compatibility

Tested in the following browsers/versions:

  • Google Chrome 7.0+
  • Internet Explorer 9.0+
  • Firefox 4.0+
  • Safari 5.1.4+
  • Mobile Safari 6.0+ (after user input)
  • Opera 12.0+
  • Microsoft Edge

Live Demos

Documentation

Contents

Quick Start

Several options to get up and running:

  • Clone the repo: git clone https://github.com/goldfire/howler.js.git
  • Install with npm: npm install howler
  • Install with Yarn: yarn add howler
  • Install with Bower: bower install howler
  • Hosted CDN: cdnjs jsDelivr

In the browser:

<script src="/path/to/howler.js"></script>
<script>
    var sound = new Howl({
      src: ['sound.webm', 'sound.mp3']
    });
</script>

As a dependency:

import {Howl, Howler} from 'howler';
const {Howl, Howler} = require('howler');

Included distribution files:

  • howler: This is the default and fully bundled source that includes howler.core and howler.spatial. It includes all functionality that howler comes with.
  • howler.core: This includes only the core functionality that aims to create parity between Web Audio and HTML5 Audio. It doesn't include any of the spatial/stereo audio functionality.
  • howler.spatial: This is a plugin that adds spatial/stereo audio functionality. It requires howler.core to operate as it is simply an add-on to the core.

Examples

Most basic, play an MP3:
var sound = new Howl({
  src: ['sound.mp3']
});

sound.play();
Streaming audio (for live audio or large files):
var sound = new Howl({
  src: ['stream.mp3'],
  html5: true
});

sound.play();
More playback options:
var sound = new Howl({
  src: ['sound.webm', 'sound.mp3', 'sound.wav'],
  autoplay: true,
  loop: true,
  volume: 0.5,
  onend: function() {
    console.log('Finished!');
  }
});
Define and play a sound sprite:
var sound = new Howl({
  src: ['sounds.webm', 'sounds.mp3'],
  sprite: {
    blast: [0, 3000],
    laser: [4000, 1000],
    winner: [6000, 5000]
  }
});

// Shoot the laser!
sound.play('laser');
Listen for events:
var sound = new Howl({
  src: ['sound.webm', 'sound.mp3']
});

// Clear listener after first call.
sound.once('load', function(){
  sound.play();
});

// Fires when the sound finishes playing.
sound.on('end', function(){
  console.log('Finished!');
});
Control multiple sounds:
var sound = new Howl({
  src: ['sound.webm', 'sound.mp3']
});

// Play returns a unique Sound ID that can be passed
// into any method on Howl to control that specific sound.
var id1 = sound.play();
var id2 = sound.play();

// Fade out the first sound and speed up the second.
sound.fade(1, 0, 1000, id1);
sound.rate(1.5, id2);
ES6:
import {Howl, Howler} from 'howler';

// Setup the new Howl.
const sound = new Howl({
  src: ['sound.webm', 'sound.mp3']
});

// Play the sound.
sound.play();

// Change global volume.
Howler.volume(0.5);

More in-depth examples (with accompanying live demos) can be found in the examples directory.

Core

Options

src Array/String [] required

The sources to the track(s) to be loaded for the sound (URLs or base64 data URIs). These should be in order of preference, howler.js will automatically load the first one that is compatible with the current browser. If your files have no extensions, you will need to explicitly specify the extension using the format property.

volume Number 1.0

The volume of the specific track, from 0.0 to 1.0.

html5 Boolean false

Set to true to force HTML5 Audio. This should be used for large audio files so that you don't have to wait for the full file to be downloaded and decoded before playing.

loop Boolean false

Set to true to automatically loop the sound forever.

preload Boolean|String true

Automatically begin downloading the audio file when the Howl is defined. If using HTML5 Audio, you can set this to 'metadata' to only preload the file's metadata (to get its duration without download the entire file, for example).

autoplay Boolean false

Set to true to automatically start playback when sound is loaded.

mute Boolean false

Set to true to load the audio muted.

sprite Object {}

Define a sound sprite for the sound. The offset and duration are defined in milliseconds. A third (optional) parameter is available to set a sprite as looping. An easy way to generate compatible sound sprites is with audiosprite.

new Howl({
  sprite: {
    key1: [offset, duration, (loop)]
  },
});

rate Number 1.0

The rate of playback. 0.5 to 4.0, with 1.0 being normal speed.

pool Number 5

The size of the inactive sounds pool. Once sounds are stopped or finish playing, they are marked as ended and ready for cleanup. We keep a pool of these to recycle for improved performance. Generally this doesn't need to be changed. It is important to keep in mind that when a sound is paused, it won't be removed from the pool and will still be considered active so that it can be resumed later.

format Array []

howler.js automatically detects your file format from the extension, but you may also specify a format in situations where extraction won't work (such as with a SoundCloud stream).

xhr Object null

When using Web Audio, howler.js uses an XHR request to load the audio files. If you need to send custom headers, set the HTTP method or enable withCredentials (see reference), include them with this parameter. Each is optional (method defaults to GET, headers default to null and withCredentials defaults to false). For example:

// Using each of the properties.
new Howl({
  xhr: {
    method: 'POST',
    headers: {
      Authorization: 'Bearer:' + token,
    },
    withCredentials: true,
  }
});

// Only changing the method.
new Howl({
  xhr: {
    method: 'POST',
  }
});

onload Function

Fires when the sound is loaded.

onloaderror Function

Fires when the sound is unable to load. The first parameter is the ID of the sound (if it exists) and the second is the error message/code.

The load error codes are defined in the spec:

  • 1 - The fetching process for the media resource was aborted by the user agent at the user's request.
  • 2 - A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.
  • 3 - An error of some description occurred while decoding the media resource, after the resource was established to be usable.
  • 4 - The media resource indicated by the src attribute or assigned media provider object was not suitable.

onplayerror Function

Fires when the sound is unable to play. The first parameter is the ID of the sound and the second is the error message/code.

onplay Function

Fires when the sound begins playing. The first parameter is the ID of the sound.

onend Function

Fires when the sound finishes playing (if it is looping, it'll fire at the end of each loop). The first parameter is the ID of the sound.

onpause Function

Fires when the sound has been paused. The first parameter is the ID of the sound.

onstop Function

Fires when the sound has been stopped. The first parameter is the ID of the sound.

onmute Function

Fires when the sound has been muted/unmuted. The first parameter is the ID of the sound.

onvolume Function

Fires when the sound's volume has changed. The first parameter is the ID of the sound.

onrate Function

Fires when the sound's playback rate has changed. The first parameter is the ID of the sound.

onseek Function

Fires when the sound has been seeked. The first parameter is the ID of the sound.

onfade Function

Fires when the current sound finishes fading in/out. The first parameter is the ID of the sound.

onunlock Function

Fires when audio has been automatically unlocked through a touch/click event.

Methods

play([sprite/id])

Begins playback of a sound. Returns the sound id to be used with other methods. Only method that can't be chained.

  • sprite/id: String/Number optional Takes one parameter that can either be a sprite or sound ID. If a sprite is passed, a new sound will play based on the sprite's definition. If a sound ID is passed, the previously played sound will be played (for example, after pausing it). However, if an ID of a sound that has been drained from the pool is passed, nothing will play.

pause([id])

Pauses playback of sound or group, saving the seek of playback.

  • id: Number optional The sound ID. If none is passed, all sounds in group are paused.

stop([id])

Stops playback of sound, resetting seek to 0.

  • id: Number optional The sound ID. If none is passed, all sounds in group are stopped.

mute([muted], [id])

Mutes the sound, but doesn't pause the playback.

  • muted: Boolean optional True to mute and false to unmute.
  • id: Number optional The sound ID. If none is passed, all sounds in group are stopped.

volume([volume], [id])

Get/set volume of this sound or the group. This method optionally takes 0, 1 or 2 arguments.

  • volume: Number optional Volume from 0.0 to 1.0.
  • id: Number optional The sound ID. If none is passed, all sounds in group have volume altered relative to their own volume.

fade(from, to, duration, [id])

Fade a currently playing sound between two volumes. Fires the fade event when complete.

  • from: Number Volume to fade from (0.0 to 1.0).
  • to: Number Volume to fade to (0.0 to 1.0).
  • duration: Number Time in milliseconds to fade.
  • id: Number optional The sound ID. If none is passed, all sounds in group will fade.

rate([rate], [id])

Get/set the rate of playback for a sound. This method optionally takes 0, 1 or 2 arguments.

  • rate: Number optional The rate of playback. 0.5 to 4.0, with 1.0 being normal speed.
  • id: Number optional The sound ID. If none is passed, playback rate of all sounds in group will change.

seek([seek], [id])

Get/set the position of playback for a sound. This method optionally takes 0, 1 or 2 arguments.

  • seek: Number optional The position to move current playback to (in seconds).
  • id: Number optional The sound ID. If none is passed, the first sound will seek.

loop([loop], [id])

Get/set whether to loop the sound or group. This method can optionally take 0, 1 or 2 arguments.

  • loop: Boolean optional To loop or not to loop, that is the question.
  • id: Number optional The sound ID. If none is passed, all sounds in group will have their loop property updated.

state()

Check the load status of the Howl, returns a unloaded, loading or loaded.

playing([id])

Check if a sound is currently playing or not, returns a Boolean. If no sound ID is passed, check if any sound in the Howl group is playing.

  • id: Number optional The sound ID to check.

duration([id])

Get the duration of the audio source (in seconds). Will return 0 until after the load event fires.

  • id: Number optional The sound ID to check. Passing an ID will return the duration of the sprite being played on this instance; otherwise, the full source duration is returned.

on(event, function, [id])

Listen for events. Multiple events can be added by calling this multiple times.

  • event: String Name of event to fire/set (load, loaderror, playerror, play, end, pause, stop, mute, volume, rate, seek, fade, unlock).
  • function: Function Define function to fire on event.
  • id: Number optional Only listen to events for this sound id.

once(event, function, [id])

Same as on, but it removes itself after the callback is fired.

  • event: String Name of event to fire/set (load, loaderror, playerror, play, end, pause, stop, mute, volume, rate, seek, fade, unlock).
  • function: Function Define function to fire on event.
  • id: Number optional Only listen to events for this sound id.

off(event, [function], [id])

Remove event listener that you've set. Call without parameters to remove all events.

  • event: String Name of event (load, loaderror, playerror, play, end, pause, stop, mute, volume, rate, seek, fade, unlock).
  • function: Function optional The listener to remove. Omit this to remove all events of type.
  • id: Number optional Only remove events for this sound id.

load()

This is called by default, but if you set preload to false, you must call load before you can play any sounds.

unload()

Unload and destroy a Howl object. This will immediately stop all sounds attached to this sound and remove it from the cache.

Global Options

usingWebAudio Boolean

true if the Web Audio API is

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号