显示来自 Blob Javascript 的视频 [英] Display a video from a Blob Javascript

查看:19
本文介绍了显示来自 Blob Javascript 的视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 HTML5 视频标签中显示来自 Javascript Blob/File 对象的视频.

I would like to display a video from a Javascript Blob/File object in the HTML5 video tag.

此代码仅适用于小视频:

This code only works for small videos :

var reader = new FileReader();
reader.onload = function(e) {
    document.getElementById("video").src=reader.result;
 }
reader.readAsDataURL(vid);

我不能将它用于大视频 (> 10MB).有没有办法在 HTML 5 中显示来自 blob 对象的大视频?

I cannot use this for big videos (> 10MB). Is there a solution to display a big video from a blob object in HTML 5?

推荐答案

我找到了.简单到我都没看到...

I've found. It was so simple that I didnt even see it...


/**
 * @param {Blob} videoFile
 * @param {HTMLVideoElement} videoEl 
 * @returns {void}
 */
function display( videoFile, videoEl ) {

    // Preconditions:
    if( !( videoFile instanceof Blob ) ) throw new Error( '`videoFile` must be a Blob or File object.' ); // The `File` prototype extends the `Blob` prototype, so `instanceof Blob` works for both.
    if( !( videoEl instanceof HTMLVideoElement ) ) throw new Error( '`videoEl` must be a <video> element.' );
    
    // 

    const newObjectUrl = URL.createObjectURL( videoFile );
        
    // URLs created by `URL.createObjectURL` always use the `blob:` URI scheme: https://w3c.github.io/FileAPI/#dfn-createObjectURL
    const oldObjectUrl = videoEl.currentSrc;
    if( oldObjectUrl && oldObjectUrl.startsWith('blob:') ) {
        // It is very important to revoke the previous ObjectURL to prevent memory leaks. Un-set the `src` first.
        // See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

        videoEl.src = ''; // <-- Un-set the src property *before* revoking the object URL.
        URL.revokeObjectURL( oldObjectUrl );
    }

    // Then set the new URL:
    videoEl.src = newObjectUrl;

    // And load it:
    videoEl.load(); // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/load
    
}

这篇关于显示来自 Blob Javascript 的视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆