Node.js 操作 OSX 系統麥克風、揚聲器音量
最近幾年 Electron 很火,公司也正好有個項目想做跨平臺客戶端,大家研究了一下就選擇了 Electron,第一次做 js 的項目遇到了不少坑,不過也都一點點解決了。
因為項目中需要對用戶錄音,HTML5 中的 API 又不支持調整麥克風音量,所以就對 Node js 操作 osx 系統麥克風、揚聲器音量了解了一下,一開始在 npm 中找了很多包都是只能操作揚聲器音量的,無法操作麥克風的音量,本來已經打算放棄了,缺無意間在網上看到 osx 系統下有自己的腳本——AppleScript,查看了官方文檔之后發現 AppleScript 確實可以控制系統的音量,由于自己完全不懂 AppleScript,只能在 npm 尋找是否有現成的解決方案,終于在 npm 中搜索一番找到了 osx-volume-controls 這個包,經過改造終于實現了這個功能。
在 OS X 系統中測試一下設置揚聲器和麥克風音量:
set volume output volume %s --100%
set volume input volume %s --100%

獲取系統的音量信息:
input volume of (get volume settings) & output volume of (get volume settings) & output muted of (get volume settings)

osx-volume-controls 要依賴到 applescript 這個包,執行下面的命令安裝到項目中:
npm i -save applescript
具體類實現代碼如下:
var applescript = require("applescript");
var scripts = {
state: "input volume of (get volume settings) & output volume of (get volume settings) & output muted of (get volume settings)",
volumeState: "output volume of (get volume settings)",
inputState: "input volume of (get volume settings)",
outputState: "output volume of (get volume settings)",
muteState: "output muted of (get volume settings)",
setOutput: "set volume output volume %s --100%",
setInput: "set volume input volume %s --100%",
increase: "set volume output volume (output volume of (get volume settings) + 10) --100%",
decrease: "set volume output volume (output volume of (get volume settings) - 10) --100%",
mute: "set volume with output muted",
unmute: "set volume without output muted"
};
var exec = function (script, callback) {
if (!callback) callback = function () {};
applescript.execString(script, callback);
};
var getScript = function (scriptName, param) {
var script = scripts[scriptName];
if (typeof param !== "undefined") script = script.replace("%s", param);
return script;
};
exports.state = function (callback) {
return exec(getScript("state"), callback);
};
exports.volumeState = function (callback) {
return exec(getScript("volumeState"), callback);
};
exports.inputState = function (callback) {
return exec(getScript("inputState"), callback);
};
exports.outputState = function (callback) {
return exec(getScript("outputState"), callback);
};
exports.muteState = function (callback) {
return exec(getScript("muteState"), callback);
};
exports.setOutput = function (volume, callback) {
return exec(getScript("setOutput", volume), callback);
};
exports.setInput = function (volume, callback) {
return exec(getScript("setInput", volume), callback);
};
exports.increase = function (callback) {
return exec(getScript("increase"), callback);
};
exports.decrease = function (callback) {
return exec(getScript("decrease"), callback);
};
exports.mute = function (callback) {
return exec(getScript("mute"), callback);
};
exports.unmute = function (callback) {
return exec(getScript("unmute"), callback);
};
使用方法(可以參照 osx-volume-controls 的文檔):
import volume from "../../utils/osxVolume.js";
volume.setInput(volumecontrol);

浙公網安備 33010602011771號