在macOS上,应用程序能否禁用/抑制所有非自身发出的系统音频输出?

在macOS上,应用程序能否禁用/抑制所有非自身发出的系统音频输出?,macos,audio,core-audio,Macos,Audio,Core Audio,在一个应用程序中,我驾驶着一台激光投影设备,使用macOS上连接的USB音频接口 激光设备将模拟音频作为输入 作为一项安全功能,如果我能将我的应用程序的音频输出设为专用输出,那将是非常好的,因为从其他应用程序或从操作系统本身发送到USB音频接口的任何其他音频都与我的激光控制音频混在一起,是不需要的,并且存在潜在的安全隐患 是否可以在macOS上使我的应用程序的音频输出具有独占性?我知道你可以在iOS上配置AVAudioSession来实现这一点(在某种程度上,你可以避开其他应用程序的音频,但通知

在一个应用程序中,我驾驶着一台激光投影设备,使用macOS上连接的USB音频接口

激光设备将模拟音频作为输入

作为一项安全功能,如果我能将我的应用程序的音频输出设为专用输出,那将是非常好的,因为从其他应用程序或从操作系统本身发送到USB音频接口的任何其他音频都与我的激光控制音频混在一起,是不需要的,并且存在潜在的安全隐患


是否可以在macOS上使我的应用程序的音频输出具有独占性?我知道你可以在iOS上配置AVAudioSession来实现这一点(在某种程度上,你可以避开其他应用程序的音频,但通知声音会反过来避开你的应用程序),但在Mac上是否可以做到这一点?它不需要与AppStore兼容。

是的,您可以请求
CoreAudio
以独占方式访问音频输出设备。这被称为占用设备。如果您占用了所有设备,那么其他应用程序(包括系统)将无法发出任何声音

对于单个设备来说,类似这样的操作可以实现:

AudioObjectPropertyAddress HOG_MODE_PROPERTY = { kAudioDevicePropertyHogMode, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
AudioDeviceID deviceId = // your audio device ID
pid_t hoggingProcess = -1; // -1 means attempt to acquire exclusive access
UInt32 size = sizeof(pid_t);

AudioObjectSetPropertyData(deviceId, &HOG_MODE_PROPERTY, 0, NULL, size, &hoggingProcess);
assert(hoggingProcess == getpid()); // check that you have exclusive access
Hog模式通过设置名为
kAudioDevicePropertyHogMode
AudioObject
属性来工作。如果设备未被占用,则该属性的值为-1。如果被占用,则该值为占用进程的进程id

如果在
Xcode
中的
kAudioDevicePropertyHogMode
上跳转到定义
,则可以读取hog mode属性的标题文档。这是了解此属性(以及
CoreAudio
中的几乎所有内容)如何工作的最佳方法

为完整起见,以下是标题文档:

                    A pid_t indicating the process that currently owns exclusive access to the
                    AudioDevice or a value of -1 indicating that the device is currently
                    available to all processes. If the AudioDevice is in a non-mixable mode,
                    the HAL will automatically take hog mode on behalf of the first process to
                    start an IOProc.
                    Note that when setting this property, the value passed in is ignored. If
                    another process owns exclusive access, that remains unchanged. If the
                    current process owns exclusive access, it is released and made available to
                    all processes again. If no process has exclusive access (meaning the current
                    value is -1), this process gains ownership of exclusive access.  On return,
                    the pid_t pointed to by inPropertyData will contain the new value of the
                    property.