I implement an audio player using AVAudioPlayer as the following.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient, with: AVAudioSessionCategoryOptions.allowBluetooth)
try? AVAudioSession.sharedInstance().setActive(true)
if let path = Bundle.main.path(forResource: "LadyGaga-MillionReasons", ofType: "mp3") {
let url = URL(string:path)
self.audioPlayer = try? AVAudioPlayer(contentsOf: url!)
self.audioPlayer?.prepareToPlay()
}
self.becomeFirstResponder()
UIApplication.shared.beginReceivingRemoteControlEvents()
}
override var canBecomeFirstResponder: Bool{
get{
return true
}
}
override var canResignFirstResponder: Bool{
get{
return true
}
}
@IBAction func btnPlay_TouchUpInsde(_ sender: Any) {
if (self.audioPlayer?.isPlaying)! {
self.audioPlayer?.pause()
self.btnPlay.setTitle("Play", for: .normal)
}else{
self.audioPlayer?.play()
self.btnPlay.setTitle("Pause", for: .normal)
}
}
override func remoteControlReceived(with event: UIEvent?) {
if let e = event , e.type == .remoteControl {
if e.subtype == UIEventSubtype.remoteControlPause {
self.audioPlayer?.pause()
}else if(e.subtype == .remoteControlPlay){
self.audioPlayer?.play()
}else if(e.subtype == .remoteControlTogglePlayPause){
if self.audioPlayer!.isPlaying {
self.audioPlayer?.pause()
}else{
self.audioPlayer?.play()
}
}
}
}
}
The app is launched, then click the play button, the audio plays ok. Then I pause the audio by a headset,and all works ok.
Another situation: The app is launched, then I want to start the audio by a headset, it does not work.
It seems to that the view is not the first responder before I click the button, even I add self.becomeFirstResponder in init function.
Who know the why the app can not get the remoteControlReceived event when do not click the button.
I implement a sample. https://github.com/leogeng/AuidoTest.git