Skip to content

Commit

Permalink
Merge pull request #5444 from watilde/fix/audio-context
Browse files Browse the repository at this point in the history
fix: initialize audio context only with user interaction
  • Loading branch information
benjiwheeler committed Jun 10, 2020
2 parents 9b0edd6 + c3b3257 commit 560a057
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/lib/audio/shared-audio-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,22 @@ import StartAudioContext from 'startaudiocontext';
import bowser from 'bowser';

let AUDIO_CONTEXT;
if (!bowser.msie) {
AUDIO_CONTEXT = new (window.AudioContext || window.webkitAudioContext)();

StartAudioContext(AUDIO_CONTEXT);
if (!bowser.msie) {
/**
* AudioContext can be initialized only when user interaction event happens
*/
const event =
typeof document.ontouchstart === 'undefined' ?
'mousedown' :
'touchstart';
const initAudioContext = () => {
document.removeEventListener(event, initAudioContext);
AUDIO_CONTEXT = new (window.AudioContext ||
window.webkitAudioContext)();
StartAudioContext(AUDIO_CONTEXT);
};
document.addEventListener(event, initAudioContext);
}

/**
Expand Down
25 changes: 25 additions & 0 deletions test/unit/util/audio-context.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import 'web-audio-test-api';
import SharedAudioContext from '../../../src/lib/audio/shared-audio-context';

describe('Shared Audio Context', () => {
const audioContext = new AudioContext();

test('returns empty object without user gesture', () => {
const sharedAudioContext = new SharedAudioContext();
expect(sharedAudioContext).toMatchObject({});
});

test('returns AudioContext when mousedown is triggered', () => {
const sharedAudioContext = new SharedAudioContext();
const event = new Event('mousedown');
document.dispatchEvent(event);
expect(sharedAudioContext).toMatchObject(audioContext);
});

test('returns AudioContext when touchstart is triggered', () => {
const sharedAudioContext = new SharedAudioContext();
const event = new Event('touchstart');
document.dispatchEvent(event);
expect(sharedAudioContext).toMatchObject(audioContext);
});
});

0 comments on commit 560a057

Please sign in to comment.