Skip to content

Commit 0f50595

Browse files
authored
Automatically attempt to resume suspended audio contexts on click (#1431)
1 parent 968f844 commit 0f50595

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

.changeset/bright-dots-crash.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"livekit-client": patch
3+
---
4+
5+
Automatically attempt to resume suspended audio contexts on click

src/room/track/utils.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,21 @@ export function getNewAudioContext(): AudioContext | void {
133133
// @ts-ignore
134134
typeof window !== 'undefined' && (window.AudioContext || window.webkitAudioContext);
135135
if (AudioContext) {
136-
return new AudioContext({ latencyHint: 'interactive' });
136+
const audioContext = new AudioContext({ latencyHint: 'interactive' });
137+
// If the audio context is suspended, we need to resume it when the user clicks on the page
138+
if (
139+
audioContext.state === 'suspended' &&
140+
typeof window !== 'undefined' &&
141+
window.document?.body
142+
) {
143+
const handleResume = () => {
144+
audioContext.resume().then(() => {
145+
window.document.body?.removeEventListener('click', handleResume);
146+
});
147+
};
148+
window.document.body.addEventListener('click', handleResume);
149+
}
150+
return audioContext;
137151
}
138152
}
139153

src/room/utils.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,7 @@ export function createAudioAnalyser(
433433
if (!audioContext) {
434434
throw new Error('Audio Context not supported on this browser');
435435
}
436+
436437
const streamTrack = opts.cloneTrack ? track.mediaStreamTrack.clone() : track.mediaStreamTrack;
437438
const mediaStreamSource = audioContext.createMediaStreamSource(new MediaStream([streamTrack]));
438439
const analyser = audioContext.createAnalyser();

0 commit comments

Comments
 (0)