了解媒体数据存储和应用的基础原理。
传统场景
1)流媒体(直播)
HLS:苹果为利用现有CDN设施而发明的"流媒体"协议
HTTP(S)-FLV:基于HTTP的流媒体协议
RTMP、RTP/RTSP、TS、MMS…
2)点播传输
HTTP(S):通过Range方式或参数方式完成Seek
Web端
HTTP(S)、WS(S)、P2P…
了解通过Web端接口可以实现哪些方向的具体应用。
let videoEl = document.createElement("video");
let types = {
'mp4': 'audio/mp4',
'MP4': 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
'webm': 'video/webm; codecs="vp8, vorbis"',
'ogg': 'video/ogg; codecs="theora, vorbis"',
'm3u8': 'application/vnd.apple.mpegURL',
'ts': 'video/mp2t; codecs="avc1.42E01E,mp4a.40.2"'
};
Object.keys(types).forEach(key => {
const type = types[key];
const ret = videoEl.canPlayType(type) || '不支持';
console.log(key + ': ' + ret);
});
基于Video时间轴控制实现交互式视频
let video = $('video');
video.ontimeupdate = ()=>{
let {currentTime} = video;
show(currentTime > 64 ? '.s2' : '.s1');
hide(currentTime > 64 ? '.s1' : '.s2');
if(
(currentTime > 64 && currentTime < 65) ||
(currentTime > 113 && currentTime < 114)
){
video.pause();
}
};
let ppBtn = $('paly_pause');
video.onplay = ()=>{
ppBtn.innerText = '暂停';
};
video.onpause = ()=>{
ppBtn.innerText = '播放';
};
ppBtn.onclick = ()=>{
video[video.paused ? 'play' : 'pause' ]();
};
$('start').onclick = ()=>{
video.currentTime = 1;
video.play();
};
$('step').onclick = ()=>{
video.currentTime = 60;
video.play();
};
$('dream').onclick = ()=>{
video.currentTime = 83;
video.play();
};
$('drink').onclick = ()=>{
video.currentTime = 116;
video.play();
};
hide('.s2');
function show(sel){
document.querySelectorAll(sel).forEach(el=>{
el.style.display='inline'
});
}
function hide(sel){
document.querySelectorAll(sel).forEach(el=>{
el.style.display='none'
});
}
function $(id){
return document.getElementById(id);
}
基于 FileReader API 播放本地文件
let iptFileEl = document.querySelector('input[type="file"]');
let videoEl = document.querySelector('video');
iptFileEl.onchange = e =>{
let file = iptFileEl.files && iptFileEl.files[0];
playFile(file);
};
function playFile(file){
if(file){
let fileReader = new FileReader();
fileReader.onload = evt => {
if(FileReader.DONE == fileReader.readyState){
videoEl.src = fileReader.result;
}else{
console.log('FileReader Error:', evt);
}
}
fileReader.readAsDataURL(file);
}else{
videoEl.src = '';
}
}
基于 getUserMedia 调用摄像头或麦克风
const getUserMediaPromise = options => new Promise((resolve, reject) => {
const nvgt = window.navigator;
if(nvgt) {
if(nvgt.mediaDevices && nvgt.mediaDevices.getUserMedia) {
return nvgt.mediaDevices.getUserMedia(options).then(resolve, reject);
}
const getUserMedia = nvgt.getUserMedia || nvgt.webkitGetUserMedia || nvgt.mozGetUserMedia;
if(getUserMedia) {
return getUserMedia(options, resolve, reject)
}
}
reject('当前环境不支持获取媒体设备。');
});
let streamTrack;
const video = document.querySelector('video');
document.querySelector('#play').onclick = () => {
getUserMediaPromise({
audio: false,
video: true
}).then(stream => {
video.srcObject = stream;
streamTrack = stream.getTracks()[0];
},
err => {
console.log('getUserMedia error: [' + err.name + '] ' + err.message)
});
};
document.querySelector('#stop').onclick = () => {
streamTrack && streamTrack.stop();
};
const box = document.querySelector('div');
document.querySelector('#sketch').onclick = () => {
box.className = box.className ==='' ? 'sketch' : '';
};
基于 getUserMedia、MediaRecorder 实现录像
const getUserMediaPromise = options => new Promise((resolve, reject) => {
const nvgt = window.navigator;
if(nvgt) {
if(nvgt.mediaDevices && nvgt.mediaDevices.getUserMedia) {
return nvgt.mediaDevices.getUserMedia(options).then(resolve, reject);
}
const getUserMedia = nvgt.getUserMedia || nvgt.webkitGetUserMedia || nvgt.mozGetUserMedia;
if(getUserMedia) {
return getUserMedia(options, resolve, reject)
}
}
reject('当前环境不支持获取媒体设备。');
});
const video = document.querySelector('#preview');
let cameraStream;
const opencameraBtn = document.querySelector('#opencamera');
const closecameraBtn = document.querySelector('#closecamera');
const recordBtn = document.querySelector('#record');
const stopRecordBtn = document.querySelector('#stoprecord');
const playBtn = document.querySelector('#play');
const downloadBtn = document.querySelector('#download');
opencameraBtn.onclick = () => getUserMediaPromise({
audio: false,
video: true
}).then(
stream => {
cameraStream = video.srcObject = stream;
opencameraBtn.disabled = true;
closecameraBtn.disabled = false;
recordBtn.disabled = false;
},
err => {
console.log('getUserMedia error: [' + err.name + '] ' + err.message)
}
);
closecameraBtn.onclick = () => {
cameraStream && cameraStream.getTracks()[0].stop();
cameraStream = null;
opencameraBtn.disabled = false;
closecameraBtn.disabled = true;
stopRecordBtn.onclick();
};
let mediaRecorder;
let recordedBlobs;
const mimeType = ['video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm', ''].find(type => {
return MediaRecorder.isTypeSupported(type);
});
// console.log('mimeType', mimeType);
recordBtn.onclick = () => {
recordedBlobs = [];
try {
mediaRecorder = new MediaRecorder(cameraStream, { mimeType });
} catch(e) {
alert('Exception while creating MediaRecorder: ' + e + '. mimeType: ' + mimeType);
return;
}
recordBtn.disabled = true;
stopRecordBtn.disabled = false;
playBtn.disabled = true;
downloadBtn.disabled = true;
mediaRecorder.onstop = evt => {
console.log('Recorder stopped');
};
mediaRecorder.ondataavailable = function(event) {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
};
mediaRecorder.start(20); // 单次收集数据毫秒时长,ondataavailable 触发频率时长间隔
};
const recordedVideo = document.querySelector('#recorded');
stopRecordBtn.onclick = () => {
mediaRecorder && mediaRecorder.stop();
mediaRecorder = null;
// console.log('Recorded Blobs: ', recordedBlobs);
recordedVideo.controls = true;
playBtn.disabled = false;
downloadBtn.disabled = false;
stopRecordBtn.disabled = true;
if(!cameraStream) {
recordBtn.disabled = true;
}
};
const getRecordedBlobUrl = () => {
const superBuffer = new Blob(recordedBlobs, {type: mimeType.split(';')[0]});
return window.URL.createObjectURL(superBuffer);
};
playBtn.onclick = () => {
recordedVideo.src = getRecordedBlobUrl();
}
downloadBtn.onclick = () => {
var a = document.createElement('a');
a.style.display = 'none';
a.href = getRecordedBlobUrl();
a.download = 'test.webm';
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
基于MediaSource播放JS拉取的媒体数据
const video = document.querySelector('video');
const fetchMp4 = (url, cb) => {
const xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
cb(xhr.response);
};
xhr.send();
};
const assetURL = 'https://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4';
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
// 创建动态媒体源,并关联到video元素上
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', () => {
const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
// 拉取数据
fetchMp4(assetURL, buf => {
sourceBuffer.addEventListener('updateend', () => {
// 媒体流传输完毕
mediaSource.endOfStream();
// video.play();
});
// 将数据喂给 Video -- 注意这里只是一次性输入整个MP4数据
sourceBuffer.appendBuffer(buf);
});
});
小结
本节通过具体的实例介绍了:视频播放控制、数据获取&采集、录制存储、创建动态媒体源播放。
本章节涉及内容配合网络存储、实时传输,可以试着实现好玩的应用,而且不限于点播或直播。
本节通过具体的实例介绍了:点播直播业务流程的不同,Web端播放器解决方案的差异。
目前来说Web端媒体选型,必须基于浏览器所支持的能力边界:如协议类型、容器类型、解码能力,亦或可自行转容器(HLS\FLV)、自行解码(WASM)的能力。
基础API:
https://developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Using_HTML5_audio_and_video
数据获取:
https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia
https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
虚拟文件:
https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
动态媒体源:
https://developer.mozilla.org/zh-CN/docs/Web/API/Media_Source_Extensions_API
数据操作:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly
https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API
画音渲染:
https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API
https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Audio_API
场景应用:
https://developer.mozilla.org/zh-CN/docs/Web/API/MediaRecorder
https://developer.mozilla.org/zh-CN/docs/Web/API/WebRTC_API
开源项目:
http://chimee.org
https://github.com/bilibili/flv.js
https://github.com/video-dev/hls.js
https://github.com/huzunjie/WasmVideoPlayer
非开源 WasmVideoPlayer 示例:
http://lab.pyzy.net/qhww