Jak*_*kob 4 audio macos core-audio
在应用程序中,我使用 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
Run Code Online (Sandbox Code Playgroud)
Hog 模式通过设置一个AudioObject名为 的属性来工作kAudioDevicePropertyHogMode。如果设备未被占用,则该属性的值为 -1。如果它被占用,则该值为占用进程的进程 ID。
如果您jump to definition继续kAudioDevicePropertyHogMode阅读,Xcode您可以阅读 hog mode 属性的标题文档。这是了解该属性(以及 中的几乎所有内容CoreAudio)如何工作的最佳方式。
为了完整起见,这是标题文档:
Run Code Online (Sandbox Code Playgroud)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.