Download an HLS stream with javascript

942 Views Asked by At

I'm trying to download an m3u8 live streaming on the browser using JavaScript (all client-side). I found this code from another question posted by @huhngut on Stack Overflow: Hls.js record file.

I wanted to ask how I could merge the audio and video streams so that I can make a single download. I'm not familiar with JavaScript, thank you very much to anyone who will help me.

var arrayRecord = [];

function download(data, filename) {
    console.log('downloading...');
    var blob = new Blob([arrayConcat(data)], {
        type: 'application/octet-stream'
    });
    saveAs(blob, filename);
}

function arrayConcat(inputArray) {
    var totalLength = inputArray.reduce(function (prev, cur) {
        return prev + cur.length
    }, 0);
    var result = new Uint8Array(totalLength);
    var offset = 0;
    inputArray.forEach(function (element) {
        result.set(element, offset);
        offset += element.length;
    });
    return result;
}

function saveAs(blob, filename) {
    var url = URL.createObjectURL(blob);
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
}

function stopRecord() {
    arrayRecord.forEach(function (item) {
        download(item.data['video'], "video.mp4");
        download(item.data['audio'], "audio.mp4");
        item.hls.destroy();
        return false;
    });
}

function startRecord() {
    var video = document.getElementById('video');
    var dataStream = {
        'video': [],
        'audio': []
    };
    var hls = new Hls();
    hls.loadSource("Your playlist");
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
        video.play();
        hls.on(Hls.Events.BUFFER_APPENDING, function (event, data) {
            console.log("apending");
            dataStream[data.type].push(data.data);
        });
    });
    arrayRecord.push({
        hls: hls,
        data: dataStream
    });
    video.onended = function (e) {
        stopRecord()
    }

}
0

There are 0 best solutions below