Skip to content
Start the AudioContext on a user action
Branch: master
Clone or download
Latest commit 8da8637 May 10, 2017
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples updating examples to new API Sep 14, 2016
.gitignore ignoring .DS_Store Sep 14, 2016
LICENSE.md adding license file Feb 25, 2016
README.md how to use with Tone.js Dec 12, 2016
StartAudioContext.js tries silent audio on touchstart for older iOS May 10, 2017
bower.json added bower package Jan 25, 2016
package.json incrementing version May 10, 2017

README.md

StartAudioContext starts the Web Audio API's AudioContext on an explicit user action.

According to the Apple's documentation:

On iOS, the Web Audio API requires sounds to be triggered from an explicit user action, such as a tap. Calling noteOn() from an onload event will not play sound.

StartAudioContext listens for the first non-dragged touchend or mouseup event on any of the given elements, then triggers a silent AudioBuffer which will start the AudioContext if it isn't already started.

Installation

Choose one:

  • download the js
  • npm install startaudiocontext
  • bower install startaudiocontext

Basic

//pass in the audio context
var context = new AudioContext();

//on iOS, the context will be started on the first valid user action on the #playButton element
StartAudioContext(context, "#playButton")

API

StartAudioContext(AudioContext, (Elements), (Callback)) => Promise

AudioContext

StartAudioContext will monitor the passed in AudioContext and resolve the promise and/or invoke the passed in callback when the AudioContext.state === 'running'.

Elements

The second argument can be an Element, Selector String, NodeList, jQuery Element or an Array of any of those. An event listener is bound to any of the passed in elements which will listen for a valid touch events to trigger a silent AudioBuffer which will start the AudioContext.

StartAudioContext(audioContext, '#button', function(){
	//audio context is started
})

If no element is passed in, it will bind to document.body.

Callback

The third argument is the callback to invoke when the AudioContext has started.

=> Promise

StartAudioContext returns a promise which is resolved when the AudioContext state is 'running'.

StartAudioContext(audioContext).then(function(){
	//context is started	
})

Tone.js

If you're using StartAudioContext with Tone.js or any other library which creates an AudioContext, pass in that AudioContext instead of creating a new one:

StartAudioContext(Tone.context, '#button').then(function(){
	//started
})

MIT License

Copyright 2016 Yotam Mann

You can’t perform that action at this time.