如何在Chrome和Mozilla等浏览器中启用WebRTC视频(以及音频)。
我正在使用的代码就是这个
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> WebRTC</title>
</head>
<body>
<video id="peer2-to-peer1" autoplay controls style="width:40%;"></video>
<script src="script.js"></script>
</body>
</html>
javascript文件:
navigator.getUserMedia ||
(navigator.getUserMedia = navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia || navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
}, function(localMediaStream) {alert('in');
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
// Do something with the video here.
};
}, onError);
} else {
alert('getUserMedia is not supported in this browser.');
}
function onSuccess() {
alert('Successful!');
}
function onError() {
alert('There has been a problem retrieving the streams - did you allow access?');
}
但是,
我收到错误,因为onSuccess函数被调用。
链接:
http://www.creativebloq.com/javascript/get-started-webrtc-1132857
答案 0 :(得分:1)
第一个问题是您不需要getUserMedia
上的视频。您的参数建议您的通话中只需要音频video: true
参数。是的,onSuccess
永远不会被调用,但这并不重要,因为你在函数调用本身内部有回调。要调用onSucess
,您的语法就像:
getUserMedia({"audio": true, "video": true}, onSuccess, onFailure);
其次,让onSuccess
获取一个参数,该参数将是媒体流。如果您希望它对媒体流执行任何操作,则需要将流src附加到onSuccess
函数中的视频src对象。
答案 1 :(得分:0)
而不是onSuccess()
你称之为:
function(localMediaStream) {alert('in');
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
// Do something with the video here.
};
}
onSuccess()
根本就没有被召唤过。
还需要从Web服务器加载文件(例如,在localhost上运行服务器)。正如教程所述,访问本地硬盘驱动器上的html文件无法正常工作。
答案 2 :(得分:0)
HTML:
<html>
<head>
<title>Record and Play Simple Messages</title>
<link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
<body>
<p>Demo for GetUserMedia()</p>
<video id="localStream"></video>
<script type="text/javascript" type="javascript" src="./js/script.js" ></script>
</body>
</html>
JS:
var video = document.querySelector('video');
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
function errorCallback(error) {
console.log('An error occurred: ' + error.code);
}
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true, audio: true}, function(stream){
if (video.mozSrcObject !== undefined) {
video.mozSrcObject = stream;
} else {
video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
}
video.play();
}, errorCallback);
} else {
console.log('getUserMedia() not supported in this browser.');
}