43

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

此代码仅适用于小视频:

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

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

4

2 回答 2

54

我找到了。太简单了,我什至没有看到它......


/**
 * @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
    
}
于 2013-01-16T14:40:14.973 回答
1

在某些情况下,应该在 createObjectURL() 方法中提供 blobObject.data。看这个简单的技巧:

function playVideo(videoStream){ // as blob 

 var video = document.querySelector('video');

 var videoUrl=window.URL.createObjectURL(videoStream.data);// blob.data gives actual data

 video.src = videoUrl;
}
于 2018-06-29T06:19:01.810 回答