17

我试图找出我使用 getUserMedia 从网络摄像头获得的图像的大小。

现在,在我的 Macbook 中,我应该有一个 720p 相机,但我得到的图像是 640x480。不过,我假设情况并非总是如此,我希望能够处理尽可能多的相机。(我更关心纵横比而不是尺寸本身,我只是想确保图片不会被拉伸)

是否有可能做到这一点?

谢谢!
丹尼尔

4

2 回答 2

21

您应该能够使用videoWidthvideoHeight属性,如下所示:

// Check camera stream is playing by getting its width
video.addEventListener('playing', function() {
    if (this.videoWidth === 0) {
        console.error('videoWidth is 0. Camera not connected?');
    }
}, false);

更新:实际上,这在 Opera 中有效,但在 Chrome 中似乎不再受支持,并且尚未在 Firefox 中实现(至少不适用于视频流)。不过,它在HTML5 规范中,因此希望在这些浏览器的路线图上。

更新2:这确实有效,但要监听的事件是“正在播放”而不是“播放”(在上面的代码中修复)。“播放”事件在play()方法返回时触发,而“正在播放”事件在播放实际开始时触发。在 Opera、Chrome 和 Firefox 中测试。

更新 3:Firefox 18 似乎反复触发“正在播放”事件,这意味着如果您在侦听器中执行大量代码,浏览器可能会停止运行。最好在触发后删除侦听器,如下所示:

var videoWidth, videoHeight;
var getVideoSize = function() {
    videoWidth = video.videoWidth;
    videoHeight = video.videoHeight;
    video.removeEventListener('playing', getVideoSize, false);
};

video.addEventListener('playing', getVideoSize, false);
于 2013-01-16T06:05:28.440 回答
1

挂钩playing事件在 Firefox 中不起作用(至少在我使用的 Ubuntu 12.04 LTS 上的 Firefox 26.0 中)。该playing事件在视频开始播放后触发一次或两次。videoWidth并且在事件触发videoHeight时为 0 或未定义。playing一种更可靠的检测方法是暂停videoWidthvideoHeight播放视频,这似乎总是有效的。下面的代码片段对我有用:

//Detect camera resolution using pause/play loop.
var retryCount = 0;
var retryLimit = 25;
var video = $('.video')[0]; //Using jquery to get the video element.
video.onplaying = function(e) {
    var videoWidth = this.videoWidth;
    var videoHeight = this.videoHeight;
    if (!videoWidth || !videoHeight) {
        if (retryCount < retryLimit) {
            retryCount++;
            window.setTimeout(function() {
                video.pause();
                video.play();
            }, 100);
        }
        else {
            video.onplaying = undefined; //Remove event handler.
            console.log('Failed to detect camera resolution after ' + retryCount + ' retries. Giving up!');
        }
    }
    else {
        video.onplaying = undefined; //Remove event handler.
        console.log('Detected camera resolution in ' + retryCount + ' retries.');
        console.log('width:' + videoWidth + ', height:' + videoHeight);
    }
};
于 2014-01-05T12:28:10.567 回答