前言
如果要在 Mac 上面做一些自動化,用指令是最方便的選擇
這篇紀錄用 AppleScript 控制音量的方法
以下內容可以在 terminal (終端機) 中執行;我是用 iTerm2
說明
取得目前的音量狀態
取得音量狀態
1
osascript -e "get volume settings"
會得到
1
output volume:1, input volume:50, alert volume:100, output muted:false
分別是
output volume:輸出音量
input volume:輸入音量 (麥克風)
alert volume:提示音量,通常是系統提示音,與輸出音量相對。(見 [2])
output muted:是否靜音
你也可以加上 of ,從結果中只取得「輸出音量」 output volume
1
2
3
osascript -e "get output volume of (get volume settings)"
# ^^^^^^^^^^^^^
# 輸出音量
結果
1
13
控制輸出音量 output volume
前面用 get 取得值,同理可用 set 來設定音量
1
osascript -e "set volume output volume 10"
設定成靜音
1
2
3
osascript -e "set volume output muted true"
# ^^^^^^^^^^^^
# 從 get volume settings 中可以看到現在是 true/false
把音量 +1
1
osascript -e "set volume output volume (output volume of (get volume settings) + 1)"
自動化?
有指令的話,要叫電腦一口氣做很多事情就很方便了。
舉簡單的例子,我們可以
開啟 Spotify,然後把音量調成 40;
然後在一個小時後,關閉 Spotify,並且把音量調回 10
1
2
3
4
5
osascript -e "tell application \"Spotify\" to activate"
osascript -e "set volume output volume 40"
delay 3600
osascript -e "tell application \"Spotify\" to if it is running then quit"
osascript -e "set volume output volume 10"
另一個例子,我們可以讓聲音漸弱,在 10 秒內從 40 降到 4。
不過我們需要借助 loop (迴圈) 與變數,會比較輕鬆
1
2
3
4
5
6
7
8
9
10
osascript < set repeat_count to 10 set volume_level to 40 repeat repeat_count times set volume output volume volume_level delay 0.5 set volume_level to volume_level - 4 end repeat EOF Note EOF 是 End Of File 的縮寫,用來標記多行的文字區塊。 我們前面的例子都是請 osascript 用 -e 執行一行指令 用 EOF 寫法代表把這段多行的 AppleScript 交給 osascript 執行 REF https://coolaj86.com/articles/how-to-control-os-x-system-volume-with-applescript/ https://support.apple.com/zh-tw/guide/mac-help/mchl9777ee30/mac