Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Commit 0be70a5

Browse files
authored
Merge pull request #706 from Borewit/fallback-blob.stream-safari
Shim `blob.stream()` for Safari < 14.1
2 parents 0992f8e + a12812b commit 0be70a5

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

lib/index.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,14 @@ const parsers: IParserTest[] = [
5353
return mm.parseBlob(blob, options);
5454
}
5555
},
56+
{
57+
methodDescription: 'parseBlob() without blob.stream being implemented',
58+
parseUrl: async (audioTrackUrl, options) => {
59+
const blob = await getAsBlob(audioTrackUrl);
60+
blob.stream = undefined; // Simulate `stream()` not being implemented by browser (e.g. Safari < 14.1)
61+
return mm.parseBlob(blob, options);
62+
}
63+
},
5664
{
5765
methodDescription: 'fetchFromUrl()',
5866
parseUrl: (audioTrackUrl, options) => {

lib/index.ts

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,43 @@ export async function parseBlob(blob: Blob, options?: IOptions): Promise<IAudioM
4343
if (blob instanceof File) {
4444
fileInfo.path = (blob as File).name;
4545
}
46-
return parseReadableStream(blob.stream(), {mimeType: blob.type, size: blob.size}, options);
46+
47+
const stream = blob.stream ? blob.stream() : convertBlobToReadableStream(blob);
48+
return parseReadableStream(stream, {mimeType: blob.type, size: blob.size}, options);
4749
}
4850

51+
/**
52+
* Convert Blob to ReadableStream
53+
* Fallback for Safari versions < 14.1
54+
* @param blob
55+
*/
56+
function convertBlobToReadableStream(blob: Blob): ReadableStream {
57+
58+
const fileReader = new FileReader();
59+
60+
return new ReadableStream({
61+
start(controller) {
62+
// The following function handles each data chunk
63+
fileReader.onloadend = event => {
64+
let data = (event.target as any).result;
65+
if (data instanceof ArrayBuffer) {
66+
data = new Uint8Array(data);
67+
}
68+
controller.enqueue(data);
69+
controller.close();
70+
};
71+
72+
fileReader.onerror = error => {
73+
controller.close();
74+
};
75+
76+
fileReader.onabort = error => {
77+
controller.close();
78+
};
79+
fileReader.readAsArrayBuffer(blob);
80+
}
81+
});
82+
}
4983
/**
5084
* Parse fetched file, using the Web Fetch API
5185
* @param audioTrackUrl - URL to download the audio track from

0 commit comments

Comments
 (0)