ios - 检测任何耳机播放/暂停前进/后退音量增大/减小按钮轻按 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 的更多信息以及更多遵循相同模式的命令。
推荐阅读
- html - 如何从 html5 脚本向 django rest 框架进行 API 调用?
- javascript - 根据活动轮播项目显示不同的数据
- c - 联合声明和定义
- c# - Environment.Exit(0) 和 Environment.Exit(Environment.ExitCode) 有什么区别?
- python - OSM Overpy 几何
- excel - 通过循环清除内容
- mongodb - 配置批处理配置器以在 Spring Batch 中包含带有 Spring Data MongoDb 的事务
- php - 在 php 中创建的文件和 kotlin 应用程序之间的数据加密
- google-app-engine - 从经过身份验证的请求中转发 OAuth 2 凭据(特别是在 GCP 中)
- swift - 广告数据显示 3 项服务,但仅发现一项