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>
This commit is contained in:
@@ -48,6 +48,12 @@ export class BackgroundAudio {
|
|||||||
source.buffer = this.sounds[url];
|
source.buffer = this.sounds[url];
|
||||||
source.loop = loop;
|
source.loop = loop;
|
||||||
source.connect(this.audioContext.destination);
|
source.connect(this.audioContext.destination);
|
||||||
|
|
||||||
|
await this.audioContext.resume();
|
||||||
|
source.onended = () => {
|
||||||
|
this.audioContext.suspend();
|
||||||
|
};
|
||||||
|
|
||||||
source.start();
|
source.start();
|
||||||
return source;
|
return source;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,16 +15,21 @@ import { logger } from "matrix-js-sdk/src/logger";
|
|||||||
import { SAMPLE_RATE } from "./VoiceRecording";
|
import { SAMPLE_RATE } from "./VoiceRecording";
|
||||||
|
|
||||||
export function createAudioContext(opts?: AudioContextOptions): AudioContext {
|
export function createAudioContext(opts?: AudioContextOptions): AudioContext {
|
||||||
|
let ctx: AudioContext;
|
||||||
if (window.AudioContext) {
|
if (window.AudioContext) {
|
||||||
return new AudioContext(opts);
|
ctx = new AudioContext(opts);
|
||||||
} else if (window.webkitAudioContext) {
|
} else if (window.webkitAudioContext) {
|
||||||
// While the linter is correct that "a constructor name should not start with
|
// While the linter is correct that "a constructor name should not start with
|
||||||
// a lowercase letter", it's also wrong to think that we have control over this.
|
// a lowercase letter", it's also wrong to think that we have control over this.
|
||||||
// eslint-disable-next-line new-cap
|
// eslint-disable-next-line new-cap
|
||||||
return new window.webkitAudioContext(opts);
|
ctx = new window.webkitAudioContext(opts);
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Unsupported browser");
|
throw new Error("Unsupported browser");
|
||||||
}
|
}
|
||||||
|
// Initialize in suspended state, as Firefox starts using
|
||||||
|
// CPU/battery right away, even if we don't play any sound yet.
|
||||||
|
void ctx.suspend();
|
||||||
|
return ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decodeOgg(audioBuffer: ArrayBuffer): Promise<ArrayBuffer> {
|
export function decodeOgg(audioBuffer: ArrayBuffer): Promise<ArrayBuffer> {
|
||||||
|
|||||||
Reference in New Issue
Block a user