Skip to content

Commit 4c00805

Browse files
Older Safari: Handle speech sample rate errors, reuse audio context (#111)
- Workaround for #110 where we've observed that the sample rate of 19000 isn't supported. We'll aim to increase the sample rate in a separate PR but this will at least mean the simulator isn't put in a bad state. - Reuse the audio context created after the user interaction, as there are limits to how many you can create on Safari 13 (4 in my BrowserStack testing). I think we always intended to do this, but careful review needed as this is a more significant change than I was anticipating. We already had clean up code for the nodes when the board stops. We never cleaned up the context. So I think we were assuming it lived forever. If this doesn't work out then an alternative is to try closing the old one before creating the new one.
1 parent 93065b4 commit 4c00805

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

src/board/audio/index.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,12 @@ export class Audio {
6767
}
6868

6969
async createAudioContextFromUserInteraction(): Promise<void> {
70-
this.context = new (window.AudioContext || window.webkitAudioContext)({
71-
// The highest rate is the sound expression synth.
72-
sampleRate: 44100,
73-
});
70+
this.context =
71+
this.context ??
72+
new (window.AudioContext || window.webkitAudioContext)({
73+
// The highest rate is the sound expression synth.
74+
sampleRate: 44100,
75+
});
7476
if (this.context.state === "suspended") {
7577
return this.context.resume();
7678
}

src/jshal.js

+14-6
Original file line numberDiff line numberDiff line change
@@ -240,14 +240,22 @@ mergeInto(LibraryManager.library, {
240240
/** @type {number} */ buf,
241241
/** @type {number} */ num_samples
242242
) {
243+
/** @type {AudioBuffer | undefined} */ let webAudioBuffer;
244+
try {
245+
// @ts-expect-error
246+
webAudioBuffer = Module.board.audio.speech.createBuffer(num_samples);
247+
} catch (e) {
248+
// Swallow error on older Safari to keep the sim in a good state.
249+
// @ts-expect-error
250+
if (e.name === "NotSupportedError") {
251+
return;
252+
} else {
253+
throw e;
254+
}
255+
}
243256
// @ts-expect-error
244257
Module.board.audio.speech.writeData(
245-
Module.conversions.convertAudioBuffer(
246-
Module.HEAPU8,
247-
buf,
248-
// @ts-expect-error
249-
Module.board.audio.speech.createBuffer(num_samples)
250-
)
258+
Module.conversions.convertAudioBuffer(Module.HEAPU8, buf, webAudioBuffer)
251259
);
252260
},
253261

0 commit comments

Comments
 (0)