Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

ios - How can i control my headset for my music player?

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
    }
}

And calling setupRemoteCommandCenter function in viewdidload

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  1. begin playing audio
  2. be the "Now playing app"

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)")
}

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...