一、在使用MSE 播放视频的时候发现firfox能播放,chrome 不能播放
原因:两边要求的fragmented mp4的格式要求不一样 , 参照Transcoding assets for Media Source Extensions - Web APIs | MDN
用ffmpeg 转成 对应的格式
firefox
ffmpeg -i mp4-264.mp4 -movflags frag_keyframe+empty_moov fmp4-264.mp4
chrome
ffmpeg -i mp4-264.mp4 -movflags frag_keyframe+empty_moov+default_base_moof fmp4-264-chrome.mp4
二、 如何知道文件什么格式
可以通过http://nickdesaulniers.github.io/mp4info/ 来查看文件
通过这个工具可以确认格式是不是fragmented. 也可以得到MIMETYPE
以下是示例代码
<html>
<head></head>
<body>
<button type="button" onclick="play()">play</button>
<video width="100%" height="100%" muted="true" autoplay="true"></video><script>
var video = document.querySelector('video');
var browserType = 0;if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1){browserType = 1;}//https://developer.mozilla.org/en-US/docs/Web/API/Media_Source_Extensions_API/Transcoding_assets_for_MSE
//## firefox 用的fragment mp4格式
//ffmpeg -i mp4-264.mp4 -movflags frag_keyframe+empty_moov fmp4-264.mp4
//## chrome 用的fragment mp4格式
//ffmpeg -i mp4-264.mp4 -movflags frag_keyframe+empty_moov+default_base_moof fmp4-264-chrome.mp4var assetURL = 'fmp4-264-chrome.mp4';
if (browserType == 1) {assetURL = 'fmp4-264.mp4';
}var mimeCodec = 'video/mp4; codecs="avc1.64001f, mp4a.40.2"';
function play() {
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {var mediaSource = new MediaSource();console.log(mediaSource.readyState); // closedvideo.src = URL.createObjectURL(mediaSource);mediaSource.addEventListener('sourceopen', sourceOpen);
} else {console.error('Unsupported MIME type or codec: ', mimeCodec);
}
}function sourceOpen (_) {console.log("sourceOpen", this.readyState); // openvar mediaSource = this;var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);fetchAB(assetURL, function (buf) {console.log("buffer")sourceBuffer.addEventListener('error', function (_) {//mediaSource.endOfStream();console.error("error ",mediaSource.readyState); // ended});sourceBuffer.addEventListener('updateend', function (_) {if (browserType === 1) { // firefoxmediaSource.endOfStream();video.play();}console.log(mediaSource.readyState); // ended});sourceBuffer.appendBuffer(buf);});
}function fetchAB (url, cb) {console.log(url);var xhr = new XMLHttpRequest;xhr.open('get', url);xhr.responseType = 'arraybuffer';xhr.onload = function () {let res = xhr.response;console.log("onload", res.byteLength)cb(xhr.response);};xhr.send();
}
</script></body>
</html>