在Mac上,触摸栏可以自动检测正在播放音频的应用程序,并允许您播放/暂停,跳过甚至搜索音频。这适用于Spotify,Quicktime甚至浏览器中的网站,例如Google Chrome上的YouTube标签。如何使用Swift获得相同的信息(歌曲名称,缩略图,正在播放歌曲的应用,时长等)?
答案 0 :(得分:2)
macOS与媒体播放器有更多的系统集成。例如,您可以向Siri询问当前歌曲,或使用“今日播放”小部件:
所有这些集成都使用Media Remote私有框架中的私有API。由于这是一个私有框架,因此如果您尝试在Mac App Store上提交应用程序,Apple将拒绝您的应用程序。您仍然可以对其进行公证以在App Store之外分发。
要使用该框架,您可以尝试以下操作:
// Load framework
let bundle = CFBundleCreate(kCFAllocatorDefault, NSURL(fileURLWithPath: "/System/Library/PrivateFrameworks/MediaRemote.framework"))
// Get a Swift function for MRMediaRemoteGetNowPlayingInfo
guard let MRMediaRemoteGetNowPlayingInfoPointer = CFBundleGetFunctionPointerForName(bundle, "MRMediaRemoteGetNowPlayingInfo" as CFString) else { return }
typealias MRMediaRemoteGetNowPlayingInfoFunction = @convention(c) (DispatchQueue, @escaping ([String: Any]) -> Void) -> Void
let MRMediaRemoteGetNowPlayingInfo = unsafeBitCast(MRMediaRemoteGetNowPlayingInfoPointer, to: MRMediaRemoteGetNowPlayingInfoFunction.self)
// Get a Swift function for MRNowPlayingClientGetBundleIdentifier
guard let MRNowPlayingClientGetBundleIdentifierPointer = CFBundleGetFunctionPointerForName(bundle, "MRNowPlayingClientGetBundleIdentifier" as CFString) else { return }
typealias MRNowPlayingClientGetBundleIdentifierFunction = @convention(c) (AnyObject?) -> String
let MRNowPlayingClientGetBundleIdentifier = unsafeBitCast(MRNowPlayingClientGetBundleIdentifierPointer, to: MRNowPlayingClientGetBundleIdentifierFunction.self)
// Get song info
MRMediaRemoteGetNowPlayingInfo(DispatchQueue.main, { (information) in
NSLog("%@", information["kMRMediaRemoteNowPlayingInfoArtist"] as! String)
NSLog("%@", information["kMRMediaRemoteNowPlayingInfoTitle"] as! String)
NSLog("%@", information["kMRMediaRemoteNowPlayingInfoAlbum"] as! String)
NSLog("%@", information["kMRMediaRemoteNowPlayingInfoDuration"] as! String)
let artwork = NSImage(data: information["kMRMediaRemoteNowPlayingInfoArtworkData"] as! Data)
// Get bundle identifier
let _MRNowPlayingClientProtobuf: AnyClass? = NSClassFromString("_MRNowPlayingClientProtobuf")
let handle : UnsafeMutableRawPointer! = dlopen("/usr/lib/libobjc.A.dylib", RTLD_NOW)
let object = unsafeBitCast(dlsym(handle, "objc_msgSend"), to:(@convention(c)(AnyClass?,Selector?)->AnyObject).self)(_MRNowPlayingClientProtobuf,Selector("a"+"lloc"))
unsafeBitCast(dlsym(handle, "objc_msgSend"), to:(@convention(c)(AnyObject?,Selector?,Any?)->Void).self)(object,Selector("i"+"nitWithData:"),information["kMRMediaRemoteNowPlayingInfoClientPropertiesData"] as AnyObject?)
NSLog("%@", MRNowPlayingClientGetBundleIdentifier(object))
dlclose(handle)
})
我假设缩略图是指专辑封面。自从您提到它们以来,Spotify,QuickTime和Google Chrome都不会与该私有API共享专辑插图。