0
我有MusicPlayer視圖控制器,您可以播放一些本地mp3文件。我需要爲我的應用程序啓用remoteControlReceived
以更改應用程序外部的音樂(播放/暫停,下一個)。我的問題是切換按鈕只適用於應用程序在MusicPlayerViewController
。例如,如果這個vc解散或去背景這些行動將不再工作! 。首先,我在安裝這些MusicPlayerViewController
通知:使用remoteControlReceived控制音樂的問題
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
編寫您有didFinishLaunchingWithOptions的代碼:分配AVAudioPlayer後。 –
@SharmaVishal謝謝!它似乎工作! –
我可以把它描述爲你的投票和回答接受的答案嗎? –