JavaScript – how to use getusermedia with Cordova on Android?
Using getusermedia to preview camera input in video elements works very well in chrome, but once the same code is run in the Cordova container, it will be interrupted. What can lead to this idea?
Example code.
Added an example of using Mozilla gum Polyfill:
(()=>{
var promisifiedOldGUM = function(constraints) {
var getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia
);
if(!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
if(navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if(navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
}
function initCamera() {
const constraints = { audio: false, video: { width: 1280, height: 720 } };
const videoElement = document.createElement('video');
videoElement.style.width = '100px';
videoElement.style.height = '100px';
document.body.appendChild(videoElement);
navigator.mediaDevices
.getUserMedia(constraints)
.then(
stream => {
videoElement.src = window.URL.createObjectURL(stream);
videoElement.onloaded@R_404_1926@data = () => {
videoElement.play();
};
}
)
.catch(
err => {
console.log('The following error occurred: ' + err.message)
}
);
}
initCamera();
})()
(please note that both the new and deprecated gum APIs do not work). This results in empty black < video > components. No errors are triggered. I initially assumed that this problem is related to androidmanifest.xml permissions and CSP, but there is no difference in fixing them
CSP configuration:
<@R_404_1926@ http-equiv="Content-Security-Policy" content="default-src 'self' android-webview-video-poster: data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src * blob:">
Androidmanifest.xml (functions and permissions)
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
resolvent:
Sorry, not enough reputation comments. I haven't seen your code, so I can't comment on it
I just got a black box on the video element
My problem was fixed by (Android 7.0):