Skip to content

Instantly share code, notes, and snippets.

@theipster
Last active January 1, 2022 03:18
Show Gist options
  • Save theipster/0d11b581cf9ce94b39fa141298605227 to your computer and use it in GitHub Desktop.
Save theipster/0d11b581cf9ce94b39fa141298605227 to your computer and use it in GitHub Desktop.
Parser for "simple" m3u8 playlists (skips integrity checks, etc.)
const downloadPlaylist = async (playlistUrl) => {
const playlist = await (await fetch(playlistUrl)).text();
const segmentUrls = playlist.split(/\r?\n/)
.map((line, index, lines) => /^#EXTINF: *([0-9]+(\.[0-9]+)?)(,.*)?/.test(line) && lines[index + 1])
.filter(segment => segment != false)
.map(segment => new URL(segment, playlistUrl).href);
const sleep = sec => new Promise(res => setTimeout(res, sec * 1000));
const segmentBlobs = [];
const now = Date.now();
for (var i = 0; i < segmentUrls.length; i++) { // Sleeping doesn't work with Array.forEach :(
await sleep(3 + (i % 4 == 3) * 7);
console.log(`Fetching at ${(Date.now() - now) / 1000}s...`);
segmentBlobs.push(await (await fetch(segmentUrls[i])).blob());
}
return URL.createObjectURL(new Blob(segmentBlobs, { type: segmentBlobs[0].type }));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment