我有MusicPlayer视图控制器,你可以播放一些本地的mp3文件。我需要启用remoteControlReceived
我的应用程序才能在应用程序之外更改音乐(播放/暂停,下一个)。我的问题是切换按钮仅在应用程序位于MusicPlayerViewController
时才有效。例如,如果这个vc解散或进入后台,那么这些操作将不再起作用! 。首先,我在MusicPlayerViewController
中设置了这些通知:
override func viewDidLoad() {
super.viewDidLoad()
//Control Music
NotificationCenter.default.addObserver(self, selector: #selector(playSong), name: NSNotification.Name("playSong"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(nextSong), name: NSNotification.Name("nextSong"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(previousSong), name: NSNotification.Name("previousSong"), object: nil)
}
然后在AppDelegate
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Play music when it's on BG
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
UIApplication.shared.beginReceivingRemoteControlEvents()
}
override func remoteControlReceived(with event: UIEvent?) {
if event!.type == UIEventType.remoteControl{
switch event!.subtype{
case UIEventSubtype.remoteControlPlay:
NotificationCenter.default.post(name: NSNotification.Name("playSong"), object: nil)
case UIEventSubtype.remoteControlPause:
NotificationCenter.default.post(name: NSNotification.Name("playSong"), object: nil)
case UIEventSubtype.remoteControlNextTrack:
NotificationCenter.default.post(name: NSNotification.Name("nextSong"), object: nil)
case UIEventSubtype.remoteControlPreviousTrack:
NotificationCenter.default.post(name: NSNotification.Name("previousSong"), object: nil)
default:
print("There is an issue with the control")
}
}
}
我无法从任何地方控制AVPlayer的问题是什么!
PS:我还在AppDelegate中设置播放音乐
答案 0 :(得分:0)
您需要在AVAudioPlayer上应用类别。 因此,您需要在分配AVAudioPlayer之后编写下面的代码。
//分配您的音频播放器&然后
a
希望这会对你有所帮助。