无法使用HTML5媒体源扩展名播放mp4视频文件

时间:2019-07-02 08:19:24

标签: javascript html mp4

使用HTML 5视频播放mp4视频时遇到一个奇怪的问题。

下面是我的html代码,在其中将“ IntroVideo.mp4”设置为存在的视频源。 我在Firefox Quantum 67.0.4(64位)和chrome 75.0.3770.100中都进行了测试,效果很好。


〜\ ClientApp \ Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <video  id="mainPlayer" class="video" 
            width="640"  height="360"
            autoplay="autoplay"  controls="controls">
                <source src="IntroVideo.mp4" />
    </video>
</body>
</html>

但是我必须使用“ MediaSource” api播放视频,在某个地方我找到了代码并按如下所示进行了修改,使用了与上述相同的mp4视频,但在两种浏览器中均无法使用。 我使用了具有以下编码信息的视频- MPEG-4(基本媒体/第2版) 视频流:AVC 音频流:AAC LC

如果我使用.webm视频,则效果很好。 请建议我..我想念什么吗?还是浏览器中编解码器支持的问题?如果是这样,则不应在上面的示例中播放。


〜\ ClientApp \ Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <video  id="mainPlayer" class="video" 
            width="640"  height="360"
            autoplay="autoplay"  controls="controls">
    </video>

    <script src="main.js"></script>
</body>
</html>

〜\ ClientApp \ main.js

try {
    if (!'MediaSource' in window)
        throw new ReferenceError('There is no MediaSource property in window object.');

    var mime = 'video/mp4; codecs="avc1.64001E"';

    if (!MediaSource.isTypeSupported(mime)) {
        alert('Can not play the media. Media of MIME type ' + mime + ' is not supported.');
        throw ('Media of type ' + mime + ' is not supported.');
    }

    var audio = document.querySelector('video'),
        mediaSource = new MediaSource();

    audio.src = URL.createObjectURL(mediaSource);

    mediaSource.addEventListener('sourceopen', function () {
        var sourceBuffer = this.addSourceBuffer(mime);
        sourceBuffer.appendWindowEnd = 4.0;
        var xhr = new XMLHttpRequest;
        xhr.open('GET', 'IntroVideo.mp4');
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            try {
                switch (this.status) {
                    case 200:
                        sourceBuffer.appendBuffer(this.response);
                        sourceBuffer.addEventListener('updateend', function (_) {
                            if (!sourceBuffer.updating && mediaSource.readyState === 'open') {
                                mediaSource.endOfStream();
                            }
                        });
                        break;
                    case 404:
                        throw 'File Not Found';
                    default:
                        throw 'Failed to fetch the file';
                }
            } catch (e) {
                console.error(e);
            }
        };
        xhr.send();
    });
} catch (e) {
    console.error(e);
}

0 个答案:

没有答案