2013-01-10 59 views
14

我試圖找出使用getUserMedia從網絡攝像頭獲得的圖像的大小。如何使用getUserMedia獲取網絡攝像頭圖像的大小?

現在,在我的Macbook中,我假設有一個720p相機,但是我得到的圖像是640x480。儘管如此,我認爲這並不總是如此,我希望能夠處理儘可能多的相機。 (我更關心長寬比比尺寸本身,我只是想確保圖片不顯示拉伸)

是否有可能這樣做?

謝謝!
丹尼爾

回答

17

您應該能夠使用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); 

UPDATE:其實,這部作品在歌劇,但似乎並沒有在Chrome中支持更多的和不是招沒有在Firefox中實現(至少不適用於視頻流)。不過,它在HTML5 spec中,所以希望能夠在這些瀏覽器的路線圖上。

更新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); 
+0

是啊,我看到了這一點,但它不是在Chrome或Firefox ...任何其他的想法?謝謝! –

+1

不怕。現在它在Chrome中停止工作了我正在尋找解決方法。對不起,我忍不住。 – tagawa

+1

明白了!經過一番實驗後,結果顯示videoWidth屬性只有在「播放」事件(而不是「播放」)被觸發後才存在。更新了上面的答案以顯示這一點。 – tagawa

1

鉤住playing事件在Firefox(在Ubuntu至少在Firefox 26.0 12.04 LTS我用)不起作用。視頻開始播放後,playing事件觸發一次或兩次。當playing事件觸發時,videoWidthvideoHeight爲0或未定義。檢測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); 
    } 
};