Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to control the camera light on a phone via a website?

Is it possible to control the camera light on a phone via a website? Say through Chrome or Firefox. I know it's possible using an Android or iOS app, which the many flashlight apps out there. And I know one can control the cameras via the getUserMedia family of functions. If not, does anyone know when it will become available?

like image 743
TinyTheBrontosaurus Avatar asked Jun 16 '16 01:06

TinyTheBrontosaurus


People also ask

Can mobile browsers access camera?

On Android devices, you can access the camera from the Browser widget. The feature is available on devices with Android OS 5.0 and later.

Can you use flashlight while using camera?

1 Tap on Camera icon from the Home screen. 2 Tap on the Switch camera icon to switch to the front camera as shown below. 3 Tap on the Flashlight icon to turn on the front flash.


1 Answers

Here is a little "torch-app" for a website:

Edit 1: I also made a jsfiddle

//Test browser support  const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;    if (SUPPORTS_MEDIA_DEVICES) {    //Get the environment camera (usually the second one)    navigator.mediaDevices.enumerateDevices().then(devices => {          const cameras = devices.filter((device) => device.kind === 'videoinput');        if (cameras.length === 0) {        throw 'No camera found on this device.';      }      const camera = cameras[cameras.length - 1];        // Create stream and get video track      navigator.mediaDevices.getUserMedia({        video: {          deviceId: camera.deviceId,          facingMode: ['user', 'environment'],          height: {ideal: 1080},          width: {ideal: 1920}        }      }).then(stream => {        const track = stream.getVideoTracks()[0];          //Create image capture object and get camera capabilities        const imageCapture = new ImageCapture(track)        const photoCapabilities = imageCapture.getPhotoCapabilities().then(() => {            //todo: check if camera has a torch            //let there be light!          const btn = document.querySelector('.switch');          btn.addEventListener('click', function(){            track.applyConstraints({              advanced: [{torch: true}]            });          });        });      });    });        //The light will be on as long the track exists          }
<button class="switch">On / Off</button>

The code is heavily inspired by this repository, this webseries and this blog-post

Edit 2: This does only works in Chrome (and maybe Opera). It does not work in Chrome on iOS, because Chrome cannot access the camera. I cannot test it on android for now. I created a new jsfiddle, with an output. If you have an android phone and it does not work for you, it will maybe tell why: https://jsfiddle.net/jpa1vwed/

Feel free to debug, comment and edit.

like image 139
Daniel Budick Avatar answered Sep 20 '22 14:09

Daniel Budick