Previewing camera input in a video element using getUserMedia
works perfectly fine in Chrome, but breaks as soon as I run the same code within a Cordova container. Any ideas what could've caused that?
Example code.
(()=>{
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.onloadedmetadata = () => {
videoElement.play();
};
}
)
.catch(
err => {
console.log('The following error occurred: ' + err.message)
}
);
}
initCamera();
})()
(note that both new and deprecated gUM APIs don't work).
This results in an empty, black <video>
element. No errors are fired.
I assumed initially that this issue was related to AndroidManifest.xml permissions and CSP, but fixing them makes no difference.
<meta 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:">
<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" />
Sorry, not enough reputation to comment. I have not read your code, so can't comment on it.
I was getting just a black box on the video element.
My problem was fixed by (Android 7.0):
Settings -> Apps -> [My App] -> Permissions -> Camera (allow)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With