如何为我的音乐播放器控制耳机? [英] How can i control my headset for my music player?

查看:290
本文介绍了如何为我的音乐播放器控制耳机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个音乐播放器iOS应用程序并从firebase获取数据。我可以在模拟器或iPhone中控制播放,暂停,下一个和上一个。耳机连接到设备播放时,下一个和上一个功能无法正常工作。
这是我用过的代码;

I am creating an music player iOS app and getting data from firebase. I can able to control play, pause, next and previous in simulator or iPhone. While headset is connect to device play, next and previous functionalities are not working properly. Here is the code which i've used;

 func setupRemoteCommandCenter() {

    // Get the shared MPRemoteCommandCenter

    let commandCenter = MPRemoteCommandCenter.shared()

    // Add handler for Play Command

    commandCenter.playCommand.addTarget { event in

            player?.play()

        print("headset play")

        return .success
    }

    // Add handler for Pause Command

    commandCenter.pauseCommand.addTarget { event in

        player?.pause()

        print("headset pause")

        return .success
    }        

    // Add handler for Next Command

    commandCenter.nextTrackCommand.addTarget { event in

        return .success
    }

    // Add handler for Previous Command

    commandCenter.previousTrackCommand.addTarget { event in

        return .success
    }
}

并且调用 setupRemoteCommandCenter 函数在 viewdidload

推荐答案

< a href =https://developer.apple.com/documentation/mediaplayer/handling_external_player_events_notifications\"rel =nofollow noreferrer>这份文件说要接收你需要的玩家事件通知

This document says that to receive player event notifications you need to


  1. 开始播放音频

  2. 成为正在播放的应用

正在播放应用的定义很难确定,但似乎是任何具有有效,不可混合的音频会话且正在播放的应用音频(或最近播放音频,这里似乎有一个短暂的宽限期)。一个可能的非混音音频会话是:

The definition of "Now playing app" is hard to pin down, but it seems to be any app that has an active, non-mixable audio session and is playing audio (or has very recently played audio, there seems to be a brief grace period here) . One possible non-mixable audio session is:

let session = AVAudioSession.sharedInstance()
do {
    try session.setCategory(AVAudioSessionCategoryPlayback)
    try session.setActive(true)
} catch let err as NSError {
    print("Error setting up non mixable audio session \(err)")
}

ps如果您希望在屏幕锁定时(或者如果您希望锁屏控件能够正常工作)耳机控件工作,您需要将音频添加到后台模式,因为从技术上讲,如果屏幕被锁定,那么您的应用已经已落地:

p.s. if you want the headset controls to work while the screen is locked (or if you want the lockscreen controls to work for that matter), you will need to add audio to Background Modes, because technically, if the screen is locked then your app has been backgrounded:

这篇关于如何为我的音乐播放器控制耳机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆