uni-app video标签打包H5Android上支持播放.m3u8 hls直播流

RobinTang

默认uni-app打包出来的H5在Android上是没法播放.m3u8直播流的,控制台或报错

Uncaught (in promise) DOMException: The element has no supported sources.

可以用hls.js来解决,在App.vue的onLaunch方法中增加加下列代码即可:

// 下面的代码增加对Android H5播放m3u8支持
// #ifdef H5
if (uni.getSystemInfoSync().platform != 'ios') {
    var script = document.createElement("script");
    script.src = "https://cdn.jsdelivr.net/npm/hls.js@latest";
    script.onload = function() {
        let init = function(video) {
            if (!video.getAttribute('hls-inited')) {
                let hls = null;
                let load = function() {
                    let src = video.src;
                    if (!src || src.indexOf('.m3u8') < 0)
                        return
                    if (!hls) {
                        hls = new Hls();
                        hls.attachMedia(video);
                    }
                    hls.loadSource(src);
                }
                video.addEventListener("error", function() {
                    load();
                }, false);
                video.addEventListener("DOMNodeRemovedFromDocument",function(){
                    if(hls){
                        hls.destroy()
                    }
                }, false);
                video.setAttribute('hls-inited', 'ok');
            }
        }
        document.getElementsByTagName("video").forEach(init)
        document.body.addEventListener("DOMNodeInserted", function(e) {
            let ele = e.relatedNode;
            if (ele.tagName === 'VIDEO') {
                init(ele);
            }
            ele.getElementsByTagName("video").forEach(init)
        })
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(script, s);
}
// #endif
阅读 2.1k

3.9k 声望
35 粉丝
0 条评论
3.9k 声望
35 粉丝
文章目录
宣传栏