• Stars
    star
    244
  • Rank 165,885 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a cross-browser WebAudio player

web-audio-player

experimental

(demo)

A simplified cross-browser WebAudio wrapper with a narrow API. This repo also attempts to report and solve some "WebAudio Gotchas" for getting WebAudio working on mobile. It targets new browsers and devices, and does not attempt to provide a non-WebAudio fallback.

See caniuse.com WebAudio API.

Motivation

The main use case for this is to support WebAudio features (such as reverb and frequency analysis) across desktop and mobile browsers.

Currently (as of Nov 2015), on recent versions of Safari and Android Chrome, you can only take advantage of these features by buffering and decoding the entire audio file (rather than streaming it).[1][2]

This module provides a consistent API whether you are using a media element (Chrome/FF) or buffer (other browsers) as the audio source.

Demo

http://jam3.github.io/web-audio-player/

The demo uses web-audio-analyser and analyser-frequency-average.

The audio streams and auto-plays on desktop. On mobile, the file is buffered, then decoded, then we wait for user to initiate playback.

Detection

You can use detect-media-element-source to approximately feature detect whether createMediaElementSource will work or not, but you may be better off just using user agent strings or defaulting to a specific behaviour for all mobile browsers.

Browser Support

Tested with the following browsers/devices.

  • Streams Audio
    • Webkit Nightly
    • FireFox 42.0
    • Chrome 46.0
  • Buffers Audio
    • Samsung Galaxy S6 (Chrome 46)
    • iOS Safari
      • iOS 9.2, iPhone 5S
      • iOS 8.3 iPad Mini Retina
    • Safari 8.0 (OSX Yosemite)
    • iOS Chrome
      • iOS 8, iPhone 6, Chrome 46
      • iOS 9.2, iPhone 5S, Chrome 45 has a gotcha (can support streaming)
      • iOS 8.3 iPad Mini Retina (can support streaming)

Install

Meant to be used with Browserify or Webpack.

npm install web-audio-player --save

Example

A simple example for Chrome/FF, which does not attempt to solve some of the mobile challenges.

var createPlayer = require('web-audio-player')

var audio = createPlayer('assets/audio.mp3')

audio.on('load', () => {
  console.log('Audio loaded...')
  
  // start playing audio file
  audio.play()
  
  // and connect your node somewhere, such as
  // the AudioContext output so the user can hear it!
  audio.node.connect(audio.context.destination)
})

audio.on('ended', () => {
  console.log('Audio ended...')
})

For a complete mobile/desktop demo, see demo/index.js. See Gotchas for more details.

Usage

NPM

player = webAudioPlayer(src, [opt])

Creates a generic audio player interface from the given src file path or array of sources. The src elements can be any of the following:

  • a string, like 'audio/foo.mp3', where the mime-type is guessed from the extension
  • an object with { src, type } which allows you to specify an exact mime-type and codec
  • a <source> DOM element

If opt.buffer is true, the audio node is created from a buffer source (not streamed). Otherwise, it is created from a media element source (streamed). The two have different implications.

Full list of options:

  • volume (Number) volume to play at
  • buffer (Boolean) whether to use a Buffer source, default false
  • loop (Boolean) whether to loop the playback, default false
  • loopStart (Number) point to restart loop in seconds, default 0
  • loopEnd (Number) point to end loop and restart in seconds, defaults to end of the audio buffer
  • crossOrigin (String) for media element sources; optional cross origin flag
  • context (AudioContext) an audio context to use, defaults to a new context. You should re-use contexts, and also consider ios-safe-audio-context
  • element (Audio|HTMLAudioElement) an optional element to use, defaults to creating a new one. Only applicable when buffer is false.
  • autoResume (Boolean) whether to resume the AudioContext during a call to play() if it's state is suspended; default true. This exists to fix a bug with Safari 9+ where the context defaults to being suspended.

When a MediaElement is used as the source, other options will be passed to simple-media-element.

⚠️ For accurate loopStart and loopEnd results, you should use a buffer source. MediaElement sources fall back to using a requestAnimationFrame timer, which is less robust, especially when the tab is out of view.

player.play()

Plays the audio, resuming it from a paused state.

player.pause()

Pauses the audio.

player.stop()

Stops the audio, settings its current time back to zero and triggering an 'end' event.

The next time play() is called, the track will start from the beginning.

properties

player.context (read-only)

The AudioContext being used for this player. You should re-use audio contexts where possible.

player.node (read-only)

The AudioNode for this WebAudio player.

This will be a GainNode that wraps the MediaElementAudioSourceNode or currently playing AudioBufferSourceNode.

player.element (read-only)

If buffer is false (the source is a media element), this will be the HTMLAudioElement or Audio object that is driving the audio.

If the source is a buffer, this will be undefined.

player.buffer (read-only)

If we are using a buffer source, this will hold the decoded AudioBuffer instance from the audio file. This will be undefined until the 'loaded' event is triggered.

If the source is a media element, this will be undefined.

player.duration (read-only)

The duration of the audio track in seconds. This will most likely only return a meaningful value after the 'load' event.

player.playing (read-only)

A read-only boolean to determine whether the audio node is currently playing.

player.volume

A getter/setter for the player.node.gain value, which allows you to adjust the volume during playback.

events

player.on('load', fn)

Called when the player has loaded, and the audio can be played. With a media element, this is after 'canplay'. With a buffer source, this is after the audio has been decoded.

player.on('end', fn)

If the audio is not looping, this is called when the audio playback ends.

This is also triggered when the stop() method is called.

player.on('error', fn)

Called with (err) parameters when there was an error loading, buffering or decoding the audio.

player.on('progress', fn)

If buffer: true, this will be called on the progress events of the XMLHttpRequest for the audio file (if the browser supports it). The parameters will be (percentage, totalBytes).

This is not called with a media element source.

player.on('decoding', fn)

If buffer: true, this will be called after the XMLHttpRequest, and before decodeAudioData starts. This alows you to provide an update to your user as the audio loads.

This is not called with a media element source.

Roadmap

Some new features may be added to this module, such as:

  • Adding a currentTime property
  • Adding a seek or play(N) feature
  • Adding a few more events
  • Supporting caching or re-using the XHR response

Please open an issue or PR if you wish to discuss a new feature.

WebAudio Gotchas

There are currently a lot of challenges with cross-platform WebAudio playback. This is likely to change soon as vendors continue fixing bugs.

  • Most browsers only support a limited number of AudioContext instances; re-use them where possible.
  • When using a buffer source that doesn't loop, the audio file will only be playable once! You will need to create another buffer source to re-play it. This module handles this for you.
  • Browsers/devices which do not support createMediaElementSource will need to download and decode the entire audio file before it can be played.
    • There is no means of getting progress callback for the decodeAudioData (this is in discussion)
  • In iOS 9.2 Chrome (v45.0.2454.89), there is a bug where opening the app directly to the demo will not play any audio. The user will need to refresh the page in order to hear audio.
  • iOS Safari has a bug with sampleRate causing playback to be distorted sometimes
  • In Chrome Android, using buffer and "Add to Home Screen", you can auto-play music without the need for user gesture. This is not the case with iOS "Add to Home Screen."
  • In iOS Safari, the <audio> tag's load() method needs to be called; however, this just causes a second (superfluous) request for the file in most other browsers.
  • In Chrome, if audioElement.load() is called immediately after audioElement.play(), no sound will occur until the next play() is called.
  • In iOS Safari, audio playback must be triggered on a 'touchend' that isn't part of a drag action. One solution is to attempt audio playback only when the distance and time since 'touchstart' is less than a certain threshold; see tap-event.
  • In Safari 9+, AudioContext state might default to "suspended" — to get around this, we resume the context when play() is called
  • In recent Chrome, you can't use datauri with crossOrigin: 'Anonymous'
  • If multiple sources are provided to Safari and the first has an error, the browser will not attempt to load any subsequent sources

See Also

Changelog

  • 1.1.0
    • play() and pause() now works the same in both modes
    • stop() added to both modes
    • volume control added
    • playing getter added
    • multiple sources can be passed; will attempt to find a working format
    • emits error when no sources can be played by browser
  • 1.0.6
    • Buffer source can only call play() / pause() once

License

MIT, see LICENSE.md for details.

More Repositories

1

math-as-code

a cheat-sheet for mathematical notation in code form
14,818
star
2

devtool

[OBSOLETE] runs Node.js programs through Chromium DevTools
JavaScript
3,774
star
3

nice-color-palettes

nice colour palettes as JSON
JavaScript
848
star
4

three-bmfont-text

renders BMFont files in ThreeJS with word-wrapping
JavaScript
764
star
5

glsl-fast-gaussian-blur

optimized single-pass blur shaders for GLSL
JavaScript
659
star
6

hihat

🎩 local Node/Browser development with Chrome DevTools
JavaScript
447
star
7

jam3-lesson-webgl-shader-threejs

Using custom vertex and fragment shaders in ThreeJS
JavaScript
361
star
8

jam3-lesson-webgl-shader-intro

A brief introduction to fragment shaders.
307
star
9

360-image-viewer

A standalone panorama viewer with WebGL
JavaScript
243
star
10

ae-to-json

will export an After Effects project as a JSON object
JavaScript
225
star
11

msdf-bmfont

Generate BMFont texture and spec using msdfgen
JavaScript
161
star
12

jam3-lesson

142
star
13

audiobuffer-to-wav

convert an AudioBuffer to .wav format
JavaScript
132
star
14

Invisible-Highway

Invisible Highway is an experiment in controlling physical things in the real world by drawing in AR. Simply make a pathway along the floor on your phone and the robot car will follow that path on the actual floor in your room. A custom highway with scenery is generated along the path to make the robots a little more scenic on your phone screen.
C#
130
star
15

awesome-streetview

beautiful [lat, lng] Google Street View locations
JavaScript
129
star
16

ffmpeg-gif

shell script to convert video to high quality GIF with ffmpeg
JavaScript
124
star
17

jam3-lesson-module-basics

intro to modular programming for frontend JavaScript
113
star
18

orbit-controls

generic controls for orbiting a target in 3D
JavaScript
110
star
19

nextjs-boilerplate

Jam3 NextJS Generator for SPA, SSG, SSR and JAMStack applications
TypeScript
107
star
20

svg-to-image

convert SVG text to a Image that can be drawn in canvas
JavaScript
103
star
21

voice-activity-detection

Voice activity detection
JavaScript
102
star
22

extract-streetview

extract street view spherical images and depth information
JavaScript
101
star
23

react-f1

F1 ui animation library for React
JavaScript
90
star
24

webgl-react-boilerplate

WebGL React App ⚡️
JavaScript
87
star
25

opentype-layout

word wraps and lays out Opentype.js glyphs
JavaScript
86
star
26

chaikin-smooth

Chaikin's smoothing algorithm for 2D polylines
JavaScript
82
star
27

f1

A stateful ui library
JavaScript
78
star
28

touch-scroll-physics

scroll physics for a scroll pane with edge bounce and velocity
JavaScript
77
star
29

preloader

A library for loading common web assets
JavaScript
69
star
30

three-png-stream

streams ThreeJS render target pixel data
JavaScript
66
star
31

layout-bmfont-text

word-wraps and lays out text glyphs
JavaScript
59
star
32

react-background-video-player

React background video component with simple player API
JavaScript
58
star
33

ios-safe-audio-context

create a WebAudio context that works in iOS and everywhere else
JavaScript
57
star
34

perspective-camera

a high-level 3D perspective camera
JavaScript
53
star
35

glsl-hsl2rgb

HSL to RGB color conversion in GLSL
GLSL
50
star
36

touches

simplified touch/mouse events for flick and swipe
JavaScript
45
star
37

ios-video-test

a test of inline iOS video playback
JavaScript
45
star
38

three-path-geometry

thick 2D lines for ThreeJS
JavaScript
42
star
39

jam3-lesson-canvas2d

open source code for a Canvas2D workshop at Jam3
JavaScript
41
star
40

maya-json-export

a generic Maya to JSON exporter for triangle meshes
JavaScript
41
star
41

glsl-100-to-300

transpiles GLSL tokens from v100 to v300 es
JavaScript
39
star
42

xhr-request

tiny http client for Node and the browser
JavaScript
39
star
43

webvr-gearvr-test

a simple test of WebVR running natively in GearVR
JavaScript
38
star
44

generator-jam3

This is a generator for Jam3 projects
JavaScript
37
star
45

google-maps-api

Get up and running with the google maps API quickly
JavaScript
34
star
46

babel-plugin-static-fs

statically transforms Node fs for the browser
JavaScript
33
star
47

ae-to-json-cli

This is a command line application to export After Effects files as JSON
JavaScript
33
star
48

tech-we-use

A list of technologies: modules, libraries, and tools we use
32
star
49

load-bmfont

loads a BMFont file in Node and the browser
JavaScript
31
star
50

jam3-testing-tools

a brief intro to testing tools
30
star
51

gl-pixel-stream

streaming gl.readPixels from an FBO
JavaScript
30
star
52

jam3-lesson-module-creation

introduction to creating a new npm module
29
star
53

threejs-generate-gif

Generate an animated GIF (using the GPU) from a threejs scene
JavaScript
29
star
54

tap-dev-tool

prettifies TAP in the browser's console
JavaScript
29
star
55

text-split

Utility for splitting text into chunks based on regex.
JavaScript
27
star
56

three-simplicial-complex

render simplicial complexes with ThreeJS
JavaScript
27
star
57

three-buffer-vertex-data

an easy way to set vertex data on a BufferGeometry
JavaScript
27
star
58

parse-dds

parses the headers of a DDS texture file
JavaScript
26
star
59

threejs-post-process-example

a tutorial on ThreeJS post processing
JavaScript
24
star
60

add-px-to-style

Will add px to the end of style values which are Numbers
JavaScript
24
star
61

google-panorama-by-location

gets a Google StreetView by [ lat, lng ]
JavaScript
24
star
62

mesh-heightmap-contours

Given a heightmap, generate a "contoured" terrain mesh
JavaScript
24
star
63

detect-import-require

list require and import paths from a JavaScript source
JavaScript
24
star
64

says

cross-platform 'say' command using Electron
JavaScript
23
star
65

background-cover

Simulate 'background-size: cover' on HTMLVideoElement and HTMLImageElement
JavaScript
23
star
66

analyser-frequency-average

gets an average intensity between two frequency ranges
JavaScript
23
star
67

webgl-components

Modular components and utilities used for WebGL based projects 💅
TypeScript
22
star
68

video-element

A simple HTML5/YouTube Video Element with a unified interface
JavaScript
22
star
69

three-fluid-demo

ThreeJS fluid simulation demo
GLSL
22
star
70

delaunify

randomly delaunay-triangulates an image
JavaScript
22
star
71

camera-unproject

unproject 2D point to 3D coordinate
JavaScript
21
star
72

heightmap-contours

Generate a series of 2D contour meshes over a heightmap
JavaScript
21
star
73

glsl-blend-overlay

blend mode 'overlay' for GLSL
C
20
star
74

ray-3d

a high-level ray picking helper for 3D intersection
JavaScript
19
star
75

scroll-manager

A handler for scrolling inside elements with different eases
JavaScript
19
star
76

touch-pinch

minimal two-finger pinch gesture detection
JavaScript
19
star
77

three-orbit-viewer

quick harness for viewing a mesh with orbit viewer
JavaScript
18
star
78

css-transform-to-mat4

Will take a string which is a css transform value (2d or 3d) and return a mat4 or 3d transformation matrix from the string.
JavaScript
17
star
79

gl-shader-output

test a shader's gl_FragColor output on a 1x1 canvas
JavaScript
17
star
80

gh-api-stream

streams JSON content from a GitHub API
JavaScript
17
star
81

uploadr

CLI tool which uploads a folder via SFTP
JavaScript
17
star
82

camera-spin

Mouse/touch-draggable first-person camera
JavaScript
17
star
83

exif-orientation-image

Properly displays an image via canvas based on the exif orientation data.
JavaScript
16
star
84

jam3-lessons-react

Quick and brief reference for React development
15
star
85

preview-dds

preview and save DDS textures from the command line
JavaScript
15
star
86

meetup-creative-coding-webgl

A WebGL experiment created for Jam3's Creative Coding Meetup on October 23rd 2019.
JavaScript
14
star
87

detect-audio-autoplay

detects whether the browser can auto-play audio
JavaScript
14
star
88

ae-threejs-multichannel-sdf

A signed distance field Effect plugin for Adobe After Effects
C
13
star
89

slot-machine-button

🎰 React Slot Machine Button
JavaScript
13
star
90

google-maps-image-api-url

This module will return a string which is a url to load an image from the Google Maps Image API
JavaScript
13
star
91

webgl-to-canvas2d

Convert a webgl context or webgl canvas into a 2d canvas
JavaScript
13
star
92

f1-dom

Create f1 ui with the dom
JavaScript
12
star
93

nyg

Not another yeoman generator, a simplified project generator based around prompts and events.
JavaScript
12
star
94

camera-picking-ray

creates a picking ray for a 2D/3D camera
JavaScript
11
star
95

scroll-bar-width

Detect browser scrollbar size
JavaScript
11
star
96

nyg-jam3

Second generation of the Jam3 Generator, many new features and breaking change features
JavaScript
11
star
97

awwwards-stream

scrape Awwwards data
JavaScript
11
star
98

adviser

Jam3 quality advisor. Integrates checking for best practices at Jam3
JavaScript
11
star
99

google-assistant-21-days-of-gratitude

JavaScript
11
star
100

google-assistant-greeting-cards

JavaScript
10
star