是否可以通过网站控制手机上的相机灯? [英] Is it possible to control the camera light on a phone via a website?
问题描述
是否可以通过网站控制手机上的相机灯?通过 Chrome 或 Firefox 说.我知道可以使用 Android 或 iOS 应用程序,那里有许多手电筒应用程序.而且我知道可以通过 getUserMedia 函数系列控制相机.如果没有,有人知道什么时候可以使用吗?
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?
推荐答案
这是一个网站的小火炬应用":
Here is a little "torch-app" for a website:
编辑 1:我还做了一个 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
编辑 2:这仅适用于 Chrome(可能还有 Opera).它在 iOS 上的 Chrome 中不起作用,因为 Chrome 不能访问相机.我现在无法在 android 上测试它.我创建了一个带有输出的新 jsfiddle.如果您有一部 android 手机并且它不适合您,它可能会说明原因:https://jsfiddle.net/jpa1vwed/
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.
这篇关于是否可以通过网站控制手机上的相机灯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!