Skip to content

Commit

Permalink
Older Safari: Handle speech sample rate errors, reuse audio context (#…
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
microbit-matt-hillsdon authored Feb 23, 2024
1 parent 93065b4 commit 4c00805
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
10 changes: 6 additions & 4 deletions src/board/audio/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,12 @@ export class Audio {
}

async createAudioContextFromUserInteraction(): Promise<void> {
this.context = new (window.AudioContext || window.webkitAudioContext)({
// The highest rate is the sound expression synth.
sampleRate: 44100,
});
this.context =
this.context ??
new (window.AudioContext || window.webkitAudioContext)({
// The highest rate is the sound expression synth.
sampleRate: 44100,
});
if (this.context.state === "suspended") {
return this.context.resume();
}
Expand Down
20 changes: 14 additions & 6 deletions src/jshal.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,14 +240,22 @@ mergeInto(LibraryManager.library, {
/** @type {number} */ buf,
/** @type {number} */ num_samples
) {
/** @type {AudioBuffer | undefined} */ let webAudioBuffer;
try {
// @ts-expect-error
webAudioBuffer = Module.board.audio.speech.createBuffer(num_samples);
} catch (e) {
// Swallow error on older Safari to keep the sim in a good state.
// @ts-expect-error
if (e.name === "NotSupportedError") {
return;
} else {
throw e;
}
}
// @ts-expect-error
Module.board.audio.speech.writeData(
Module.conversions.convertAudioBuffer(
Module.HEAPU8,
buf,
// @ts-expect-error
Module.board.audio.speech.createBuffer(num_samples)
)
Module.conversions.convertAudioBuffer(Module.HEAPU8, buf, webAudioBuffer)
);
},

Expand Down

0 comments on commit 4c00805

Please sign in to comment.