在swift上检测任何耳机播放/暂停前向/后向音量增大/减小按钮



我正在尝试构建一个音频播放器应用程序!我不知道如何让我的应用程序负责播放/暂停前向/后向音量增大/减小按钮,从任何耳机或头戴式耳机点击或点击!我从苹果公司找到了这个页面!但这对我来说是不可理解的!我喜欢有一个示例代码!

链接:https://developer.apple.com/documentation/mediaplayer/mpremotecommand

假设您已经有了处理媒体播放的类,那么剩下的就很容易了。

如您提供的链接中所述,任何与媒体相关的事件都会发送给正在收听的应用程序,无论事件来自哪里(控制中心、耳机…(,该部分都由媒体播放器框架处理

在您需要获取MPF(媒体播放器框架(的命令中心并设置事件将触发的函数的类上,我将只显示您提供的链接中的函数。

class MediaPlayer {
let commandCenter = MPRemoteCommandCenter.shared()
init() {
// this is for the play command, check the docs for more commands
commandCenter.playCommand.addTarget { [unowned self] event in
if self.player.rate == 0.0 { // <- is stopped?
// do your stuff and say to the OS that everything worked
return .success
}
// if the command does not run properly you must inform the OS
return .commandFailed
}
}
}

有一些缺失的代码取决于您的实现,但您想要的是这里,现在当有东西触发";播放";命令您的应用程序将检测到它,如果播放器没有再现任何媒体,它将启动。

你可以在文档中看到更多关于MPRemoteCommandCenter的信息,也可以看到更多遵循相同模式的命令。

最新更新