Skip to content

Instantly share code, notes, and snippets.

@Richienb
Created May 4, 2020 15:35
Show Gist options
  • Save Richienb/346b8faa7800f57d64d951393e85da98 to your computer and use it in GitHub Desktop.
Save Richienb/346b8faa7800f57d64d951393e85da98 to your computer and use it in GitHub Desktop.
Flashlight control
"use strict";
let isOn = false;
let track_
const lastItem = array => array[array.length - 1]
exports.on = async () => {
if ("mediaDevices" in navigator) {
const devices = await navigator.mediaDevices.enumerateDevices()
const cameras = devices.filter(({kind}) => kind === "videoinput")
if (cameras.length === 0) {
throw new Error("No cameras found!")
}
const camera = lastItem(cameras)
const stream = await navigator.mediaDevices.getUserMedia({
video: {
deviceId: camera.deviceId,
facingMode: ['user', 'environment'],
height: {
ideal: 1080
},
width: {
ideal: 1920
}
}
})
const [track] = stream.getVideoTracks();
const imageCapture = new ImageCapture(track)
await imageCapture.getPhotoCapabilities()
track.applyConstraints({
advanced: [{
torch: true
}]
});
track_ = track
isOn = true;
} else {
throw new Error("Not supported!")
}
};
exports.off = () => {
if (!writableStream.isTTY) {
return;
}
if (track_) {
track_.stop()
track_ = undefined
}
isOn = false;
};
exports.toggle = (force) => {
if (force !== undefined) {
isOn = force;
}
if (isOn) {
exports.on(writableStream);
} else {
exports.off(writableStream);
}
};
MIT License
Copyright (c) 2020 Richie Bendall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment