检测 Mac 上的音频输出?

Detect Audio Output on Mac?

有没有办法检测Mac系统是否正在输出音频?无论是通过耳机插孔、USB-C 还是蓝牙,是否有当且仅当音频正在播放时运行的进程?

我制作了一个播放 15hz 正弦波的 unix 脚本,其想法是当且仅当没有播放音频时每 580 秒执行一次脚本。如果正在播放音频,脚本将不会执行。

我有非常好的扬声器,但缺点是它们每 10 分钟(600 秒)进入一次 'standby' 节电模式。当我在工作时,我并不真正关心它是否在后台运行*但当我在家时,当扬声器进入待机状态时,我往往会错过通知,所以脚本的目的是播放 3当且仅当没有播放音频时,每 580 秒出现第二个波形。

我不确定这是否与您想要的超级相关,但也许可以试试 Soundflower?在 mac.

中重新路由音频非常有用

您不一定需要使用 AppleScript 来实现目标,但如果您愿意,当然可以。

我会选择使用 启动代理,如下面的 示例 XML plist 代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.my.play.if.no.audio.is.playing</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>-c</string>
        <string>[[ $(pmset -g | grep ' sleep') =~ coreaudiod ]] || '/path/to/shell_script'</string>
    </array>
    <key>RunAtLoad</key>
    <false/>
    <key>StartInterval</key>
    <integer>580</integer>
</dict>
</plist>

XMLplistcode中的'/path/to/shell_script'改成实际的fully qualified您的 shell 脚本.

的路径名

然后保存为 ~/Library/LaunchAgents/ 中的 com.my.play.if.no.audio.is.playing.plist 并使用 Terminal 加载它,例如:

cd ~/Library/LaunchAgents/
launchctl load com.my.play.if.no.audio.is.playing.plist

然后如果没有音频播放,您的 shell 脚本 将每隔 580 秒 执行一次。


备注:

如编码所示,它假定 可执行位 已在您的 shell 脚本 .

上设置

如果您打算使用 Launch AgentsLaunch Daemons,我强烈建议您阅读 手册页 对于 launchctllaunchd.plistlaunchd

您可以在 Terminal 中阅读 command 的手册页输入man command,然后按输入,或为了便于阅读,只需输入command 然后右击它 select: 打开手册页

终端中停止您的Launch Agent

cd ~/Library/LaunchAgents/
launchctl unload com.my.play.if.no.audio.is.playing.plist

您也可以在 shell 脚本 中包含 测试条件 ,例如:

#!/bin/bash

if [[ ! $(pmset -g | grep ' sleep') =~ coreaudiod ]]; then

    # Code to generate your sine waveform goes here.

fi

然后,在示例中使用的命令 XML plist code 将是:

    <key>ProgramArguments</key>
    <array>
        <string>/path/to/shell_script</string>
    </array> 


如果您真的想使用 AppleScript,并假设有一个 Stay Open application,然后:

示例 AppleScript 代码:

on run
    --  # Add any AppleScript code you what run when the
    --  # Stay Open AppleScript application is opened.
    
end run

on idle
    
    do shell script ¬
        "[[ $(pmset -g | grep ' sleep') =~ coreaudiod ]] || '/path/to/shell_script'"
    
    return 580
    
end idle

on quit
    continue quit
end quit

备注:

脚本编辑器AppleScript 代码中保存示例AppleScript =120=] , 设置 文件格式: [Application] and [√] 在 运行 handler.[=27= 后保持打开状态]

如果您将 测试条件 添加到您的 shell 脚本 ,如上所示,那么您的 do shell script 命令 将是:

do shell script "'/path/to/shell_script'"

我倾向于避免使用这种类型的 AppleScript 应用程序,因为我发现随着时间的推移它们 can/may成为资源密集型,因为它们继续消耗更多 RAM。 YMMV.