我想通过 Mac 上的 CLI 检查当前音量级别。我知道我可以这样设置:
osascript -e 'set volume <N>'
但在尝试获取当前音量级别时,这似乎不起作用。
$ osascript -e 'get volume'
4:10: execution error: The variable volume is not defined. (-2753)
答案1
您应该发现它将get volume settings
返回一个对象,其中包含输出量和警报量。例如,您可以这样做来检索整个对象:
osascript -e 'get volume settings'
或者更确切地说,这可能只是获取输出量(例如,而不是警报量):
osascript -e 'set ovol to output volume of (get volume settings)'
...但请注意,并非所有音频设备都可以通过软件直接控制音量设置。例如,您的显示音频应该具有控制权;然而,火线或 USB I/O 板可能不会在软件控制下进行这些设置(因为它们可能是物理旋钮)。如果特定设置不受软件控制,那么它将在返回的对象中显示为get volume settings
“缺失值”或类似的内容。
答案2
使用相同的比例 1..100 获取和设置音量:
# Get current volume as a number from 0 to 100
current_vol=$(osascript -e 'output volume of (get volume settings)')
# Prank co-worker by playing loud noise/music
osascript -e "set volume output volume 100"
afplay sabotage.m4a
# (Re-)set to saved volume as a number from 0 to 100
osascript -e "set volume output volume $current_vol"
答案3
我提交了一个非常简单的 bash 脚本,名为“chut”。因为我厌倦了 sys 卷需要浮点作为输入(0 到 10 步长 0.1),但输出步长 14 范围从 0 到 100 的整数。
想想看...如果有人感兴趣:http://github.com/docgyneco69/chut
尽显其荣耀:
#!/bin/bash
## CHUT script
## Note: regex [[:digit:]] requires a relatively recent shell
## easy to change with a sed cmd if needed
## applescript arg is not fully bullet proofed for sneaky cmds
## but as no outside arg is passed by the script I kept the usual
## arg format for code readibility (and pure laziness)
# init _x and curr_vol with defaults values (muting)
_x='- 100' ; curr_vol='0' ;
function _usage {echo -e "CHUT is a simple cmd exe to change the system audio volume.
USAGE chut [][-][--][+][++]
no arg will mute (default)
[-][+] [--][++] to decrease or increase the volume
[+++] to set to the maximum
[-h][--help] display this message
NOTE sys sets volume as float (0-10/0.1) but outputs int (0-100/14)" ; exit 1 ; } ;
# set _x by looping $1 then break as we only use 1st arg, -h or --help to print usage
while [[ "$1" ]]; do case "$1" in
"-h"|"--help") _usage ;;
"-") _x='- 0.5' ;;
"--") _x='- 1.0' ;;
"+") _x='+ 0.5' ;;
"++") _x='+ 1.0' ;;
"+++") _x='+ 100' ;;
*) _x='- 100' ;; # unrecognized values will mute
esac ; break ; done ;
# get current volume value from system (sys volume is 0 to 100 step 14)
curr_vol=$(/usr/bin/osascript -e "get volume settings" | cut -d ',' -f1 | tr -dc [[:digit:]]) ;
# set new volume via _x - use bc for floating point, escape potential errors,
# print value with one decimal - test & echo the new volume value via applescript
curr_vol=$( printf "%.1f" "$( echo "$curr_vol / 14 $_x" | bc -l 2>&-)" ) ;
(/usr/bin/osascript -e "set Volume "\"$curr_vol"\" ") && \
echo $(/usr/bin/osascript -e "get volume settings" | cut -d ',' -f1 | tr -dc [[:digit:]]) ;
exit 0 ;