首页 > 解决方案 > 检测任何耳机播放/暂停前进/后退音量增大/减小按钮轻按 swift

问题描述

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

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

标签: iosswift

解决方案


假设你已经有了处理媒体播放的类,剩下的就很简单了。

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

在类上,您需要获取 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 的更多信息以及更多遵循相同模式的命令。


推荐阅读