我想访问getUserMedia之外的streamObject。这是代码。通常你会在成功回调中运行脚本函数,但我不这样做,因为函数getUserMedia被多次使用,我不想重复编码相同的函数。
var streamObject;
requestDevices = {
media:function(){
navigator.getUserMedia(
{video:true, audio:true},
function(stream){
streamObject = stream;
return streamObject //not working
});
}
};
/
stream = {
// I need the streamObject here
startStream:function(stream){
pc.addStream(streamObject);
//blah blah blah
}
}
我也试过下面的代码,但是没有用,因为myCallback首先需要流式传输..
media:function(myCallback){
navigator.getUserMedia(
{video:true, audio:true},
function(stream){
streamObject = stream;
return streamObject;
stream.startStream(streamObject);
});
}
答案 0 :(得分:1)
您可以/必须使用Promise
,例如:
var requestDevices = {
media:function() {
return new Promise(function(resolve, reject) {
navigator.getUserMedia({ video: true, audio: true }, resolve, reject);
});
}
};
var stream = requestDevices.media();
无论您何时需要流对象:
stream.then(function(s) {
Stream.startStream(s);
});
// Somewhere else
stream.then(function(s) {
...
});
正如@jib所说,getUserMedia
的更新语法本身支持Promise
,所以你可以这样做:
var stream = navigator.mediaDevices.getUserMedia({ ... })
现在您还需要adapter.js polyfill。