Skip to content

Commit 560a057

Browse files
authored
Merge pull request scratchfoundation#5444 from watilde/fix/audio-context
fix: initialize audio context only with user interaction
2 parents 9b0edd6 + c3b3257 commit 560a057

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/lib/audio/shared-audio-context.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,22 @@ import StartAudioContext from 'startaudiocontext';
22
import bowser from 'bowser';
33

44
let AUDIO_CONTEXT;
5-
if (!bowser.msie) {
6-
AUDIO_CONTEXT = new (window.AudioContext || window.webkitAudioContext)();
75

8-
StartAudioContext(AUDIO_CONTEXT);
6+
if (!bowser.msie) {
7+
/**
8+
* AudioContext can be initialized only when user interaction event happens
9+
*/
10+
const event =
11+
typeof document.ontouchstart === 'undefined' ?
12+
'mousedown' :
13+
'touchstart';
14+
const initAudioContext = () => {
15+
document.removeEventListener(event, initAudioContext);
16+
AUDIO_CONTEXT = new (window.AudioContext ||
17+
window.webkitAudioContext)();
18+
StartAudioContext(AUDIO_CONTEXT);
19+
};
20+
document.addEventListener(event, initAudioContext);
921
}
1022

1123
/**

test/unit/util/audio-context.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import 'web-audio-test-api';
2+
import SharedAudioContext from '../../../src/lib/audio/shared-audio-context';
3+
4+
describe('Shared Audio Context', () => {
5+
const audioContext = new AudioContext();
6+
7+
test('returns empty object without user gesture', () => {
8+
const sharedAudioContext = new SharedAudioContext();
9+
expect(sharedAudioContext).toMatchObject({});
10+
});
11+
12+
test('returns AudioContext when mousedown is triggered', () => {
13+
const sharedAudioContext = new SharedAudioContext();
14+
const event = new Event('mousedown');
15+
document.dispatchEvent(event);
16+
expect(sharedAudioContext).toMatchObject(audioContext);
17+
});
18+
19+
test('returns AudioContext when touchstart is triggered', () => {
20+
const sharedAudioContext = new SharedAudioContext();
21+
const event = new Event('touchstart');
22+
document.dispatchEvent(event);
23+
expect(sharedAudioContext).toMatchObject(audioContext);
24+
});
25+
});

0 commit comments

Comments
 (0)