UNPKG

win-audio

Version:

Get, Set and Watch Speaker/Microphone Volume on Windows

124 lines (123 loc) 3.19 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = __importDefault(require("events")); const bindings_1 = __importDefault(require("bindings")); const audio = (0, bindings_1.default)("../build/Release/audio.node"); const initDevice = (device) => { const events = new events_1.default(); const data = { audio: audio.get(device), status: audio.isMuted(device), }; let interval; /** * Check and update current volume. [Generic] */ const update = (fn, key, event) => { let now = fn(Number(device)); if (key === "status") { now = Boolean(now); } if (data[key] !== now) { events.emit(event, { old: data[key], new: now, }); } data[key] = now; }; /** * Check and update current volume. */ const check = () => { update(audio.get, "audio", "change"); update(audio.isMuted, "status", "toggle"); }; /** * Get current audio */ const get = () => audio.get(device); /** * Update current and delegate audio set to native module. */ const set = (value) => { audio.set(value, device); check(); }; /** * Save current status and mute volume. */ const mute = () => audio.mute(device, 1); /** * Restore previous volume. */ const unmute = () => audio.mute(device, 0); /** * Mute/Unmute volume. */ const toggle = () => { const fn = audio.isMuted(device) ? unmute : mute; fn(); }; /** * React to volume changes using polling check. */ const start = (every) => { interval = setInterval(check, every || 500); }; /** * Stop polling check. */ const stop = () => { clearInterval(interval); }; /** * Increase current volume of value% */ const increase = (value) => { unmute(); set(Math.min(Math.max(0, data.audio + value), 100)); }; /** * Decrease current volume of value% */ const decrease = (value) => increase(-value); /** * Check if is muted */ const isMuted = () => audio.isMuted(device) === 1; return { // Events on: (event, cb) => events.on(event, cb), off: (event, cb) => events.off(event, cb), once: (event, cb) => events.once(event, cb), removeAllListeners: () => events.removeAllListeners(), // Methods start, stop, get, set, increase, decrease, mute, unmute, isMuted, toggle, }; }; const instances = {}; const proxy = new Proxy({}, { get: (_, prop) => { let instance = instances[prop]; if (!instance) { instance = initDevice(prop === "mic" ? 1 : 0); instances[prop] = instance; } return instance; }, }); exports.default = proxy; module.exports = proxy;