在 Mac 上检测音频输出?

时间:2021-06-10 14:21:08

标签: bash audio io scripting applescript

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

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

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

3 个答案:

答案 0 :(得分:0)

我不确定这是否与您想要的非常相关,但也许可以试试 Soundflower ?这对于在 mac 中重新路由音频非常有用。

答案 1 :(得分:0)

您不一定需要使用 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>

XML plist 代码中的'/path/to/shell_script'更改为shell脚本的实际完全限定路径名 em>.

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

终端 加载它
cd ~/Library/LaunchAgents/
launchctl load com.my.play.if.no.audio.is.playing.plist

然后每 580 秒如果没有音频播放,你的 shell 脚本就会执行一次。


注意事项:

按照编码,它假定 可执行位已在您的 shell 脚本上设置。

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

您可以在终端中输入command阅读手册页man command em>,然后按 enter,或者为了更容易阅读,只需输入 command 然后右键单击它并选择: 打开手册页

要在终端中停止您的启动代理

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 代码中使用的命令将是:

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


如果您真的想使用 AppleScript,并假设有一个 保持开放 应用程序,那么:

示例 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 代码时,设置文件格式:[应用程序][√] 运行后保持打开状态

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

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

我倾向于避免使用这种类型的 AppleScript 应用程序,因为我发现随着时间的推移,它们可以/可能会变得资源密集,因为它们会继续消耗更多<强>内存。天啊。

答案 2 :(得分:-1)

试试这个:

do shell script "if [[ \"$(pmset -g | grep ' sleep')\" == *\"coreaudiod\"* ]]; then echo audio is playing; else echo no audio playing;  fi"