网页前端video播放m3u8(HLS)
网页前端video播放m3u8(HLS)
HLS (HTTP Live Streaming)是Apple公司研发的流媒体传输技术,包括一个m3u8的索引文件、多个ts分片文件和key加密串文件。这项技术主要应用于点播和直播领域。
开源JS库(Github):
【video.js】https://github.com/videojs/videojs-contrib-hls
【hls.js】https://github.com/video-dev/hls.js/
腾讯视频SDK(TCPlayerLite),文档地址:https://cloud.tencent.com/document/product/881/20207
DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>videojs-contrib-hls embedtitle>
<link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
<script src="https://unpkg.com/video.js/dist/video.js">script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js">script>
head>
<body>
<h1>Video.js Example Embedh1>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268"
data-setup='{}'>
<source src="http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8" type="application/x-mpegURL">
video>
<script>
script>
body>
html>
注:可以指定多个source标签。
DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>前端播放m3u8格式视频title>
<link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
<script src='https://vjs.zencdn.net/7.4.1/video.js'>script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.15.0/videojs-contrib-hls.min.js" type="text/javascript">script>
head>
<body>
<style>
.video-js .vjs-tech {position: relative !important;}
style>
<div>
<video id="myVideo" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" data-setup='{}' style='width: 100%;height: auto'>
<source id="source" src="http://1252093142.vod2.myqcloud.com/4704461fvodcq1252093142/48c8a9475285890781000441992/playlist.m3u8" type="application/x-mpegURL">source>
video>
div>
<div class="qiehuan" style="width:100px;height: 100px;background: red;margin:0 auto;line-height: 100px;color:#fff;text-align: center">切换视频div>
body>
<script>
// videojs 简单使用
var myVideo = videojs('myVideo', {
bigPlayButton: true,
textTrackDisplay: false,
posterImage: false,
errorDisplay: false,
})
myVideo.play()
var changeVideo = function (vdoSrc) {
if (/\.m3u8$/.test(vdoSrc)) { //判断视频源是否是m3u8的格式
myVideo.src({
src: vdoSrc,
type: 'application/x-mpegURL' //在重新添加视频源的时候需要给新的type的值
})
} else {
myVideo.src(vdoSrc)
}
myVideo.load();
myVideo.play();
}
var src = 'http://1252093142.vod2.myqcloud.com/4704461fvodcq1252093142/f865d8a05285890787810776469/playlist.f3.m3u8';
document.querySelector('.qiehuan').addEventListener('click', function () {
changeVideo(src);
})
script>