检测屏幕是否正在录制在macOS上

时间:2020-03-26 14:24:58

标签: swift cocoa nswindow nsstatusitem screen-recording

我正在寻找一种方法来检测当前是否正在录制屏幕。
理想情况下,记录开始/停止的事件。也许是某种分布式通知。

我的用例是,我想在录制屏幕(选择加入)时隐藏我的应用程序的菜单栏项目,因为它显示日期和时间,并且许多用户不希望屏幕记录中包含时间。

我尝试将.none窗口的NSWindow#sharingType设置为NSStatusBarButton,但是该选项似乎仅适用于屏幕截图。

答案应为Swift。

1 个答案:

答案 0 :(得分:0)

我有一个有效的答案,依靠AppleScript查询QuickTime Player。对于经过强化运行时的沙盒应用程序,这需要几步,包括权利以及特殊的plist键,提示用户授予对您的应用程序的访问权限以编写QuickTime Player脚本。

如果这些都不是破坏交易的方法,那么这是一个小类,该类可检测到QuickTime Player是否正在运行,如果是,则发送AppleScript来查询“屏幕录制”文档。如果正在进行屏幕录像(不仅仅是打开等待录像),则文档的当前时间将大于0,并且脚本结果为true,否则为false。还可以在尝试脚本之前检查一下QuickTime Player是否正在运行。如果不是,则返回false。

import Cocoa

class ScreenRecordingCheck {
    static let qt_query_applescript = """
tell application id "com.apple.QuickTimePlayerX"
    set isScreenRecording to false
    repeat with doc in documents
        set docname to name of doc
        if docname is "Screen Recording" then
            set doctime to current time of doc
            set isScreenRecording to doctime is greater than 0.0
        end if
    end repeat
    set result to isScreenRecording
end tell
"""

    var scriptObj: NSAppleScript?

    init() {
        self.scriptObj = NSAppleScript(source: ScreenRecordingCheck.qt_query_applescript)
    }

    func isScreenRecordingActive() -> Bool {
        var result = false
        if !self.isQuicktimePlayerRunning() {
            return false
        }
        if let script = self.scriptObj {
            var errDictionary: NSDictionary?
            let scriptResult = script.executeAndReturnError(&errDictionary)
            if let err = errDictionary {
                Swift.print("Error: " + String(describing:err))
            } else {
                result = scriptResult.booleanValue
            }
        }
        return result
    }

    func isQuicktimePlayerRunning() -> Bool {
        let qtapps = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.QuickTimePlayerX")
        return !qtapps.isEmpty
    }
}

要在沙盒应用程序中启用此功能,您需要将此密钥添加到应用程序的Info.plist中:

<key>NSAppleEventsUsageDescription</key>
<string>Please give ScreenRecordingDetector access to Quicktime Player via Apple Script.</string>

...以及应用程序的.entitlements文件中的此项:

<key>com.apple.security.temporary-exception.apple-events</key>
<string>com.apple.QuickTimePlayerX</string>

除了选中应用目标的“签名和功能/强化运行时”下的 Apple Events 复选框。

相关问题