Skip to content

Commit 02dd79f

Browse files
mbachryt3chguy
andauthored
Fix battery drain from Web Audio (#29203)
* Fix battery drain from Web Audio * move suspend away from constructor * await on resume() * Delint Signed-off-by: Michael Telatynski <7t3chguy@gmail.com> --------- Signed-off-by: Michael Telatynski <7t3chguy@gmail.com> Co-authored-by: Michael Telatynski <7t3chguy@gmail.com>
1 parent 160a7c1 commit 02dd79f

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

src/audio/BackgroundAudio.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ export class BackgroundAudio {
4848
source.buffer = this.sounds[url];
4949
source.loop = loop;
5050
source.connect(this.audioContext.destination);
51+
52+
await this.audioContext.resume();
53+
source.onended = () => {
54+
this.audioContext.suspend();
55+
};
56+
5157
source.start();
5258
return source;
5359
}

src/audio/compat.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,21 @@ import { logger } from "matrix-js-sdk/src/logger";
1515
import { SAMPLE_RATE } from "./VoiceRecording";
1616

1717
export function createAudioContext(opts?: AudioContextOptions): AudioContext {
18+
let ctx: AudioContext;
1819
if (window.AudioContext) {
19-
return new AudioContext(opts);
20+
ctx = new AudioContext(opts);
2021
} else if (window.webkitAudioContext) {
2122
// While the linter is correct that "a constructor name should not start with
2223
// a lowercase letter", it's also wrong to think that we have control over this.
2324
// eslint-disable-next-line new-cap
24-
return new window.webkitAudioContext(opts);
25+
ctx = new window.webkitAudioContext(opts);
2526
} else {
2627
throw new Error("Unsupported browser");
2728
}
29+
// Initialize in suspended state, as Firefox starts using
30+
// CPU/battery right away, even if we don't play any sound yet.
31+
void ctx.suspend();
32+
return ctx;
2833
}
2934

3035
export function decodeOgg(audioBuffer: ArrayBuffer): Promise<ArrayBuffer> {

0 commit comments

Comments
 (0)