如何控制我的音乐播放器的耳机? [英] How can i control my headset for my music player?
问题描述
我正在创建一个音乐播放器 iOS 应用程序并从 firebase 获取数据.我可以在模拟器或 iPhone 中控制播放、暂停、下一首和上一首.当耳机连接到设备播放时,下一个和上一个功能无法正常工作.这是我使用的代码;
func setupRemoteCommandCenter() {//获取共享的 MPRemoteCommandCenter让 commandCenter = MPRemoteCommandCenter.shared()//为播放命令添加处理程序commandCenter.playCommand.addTarget { 事件在播放器?.play()打印(耳机播放")返回 .success}//为暂停命令添加处理程序commandCenter.pauseCommand.addTarget { 事件在播放器? .pause()打印(耳机暂停")返回 .success}//为下一个命令添加处理程序commandCenter.nextTrackCommand.addTarget { 事件在返回 .success}//为上一个命令添加处理程序commandCenter.previousTrackCommand.addTarget { 事件在返回 .success}}
并在viewdidload
setupRemoteCommandCenter
函数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
This document says that to receive player event notifications you need to
- begin playing audio
- 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:
这篇关于如何控制我的音乐播放器的耳机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!