Reputation: 2068
There is quit of similar OPs per googles but I didn't fix my issue by following them. It seems I'm closed but still cannot figure out where is wrong, appreciate any hint here.
My AudioPlayer is put in a separate file as Singleton pattern
class AudioPlayer {
// Singleton to keep audio continue to play when switching viewControllers
static let shared = AudioPlayer()
var player: AVAudioPlayer?
private init() {}
func play(url: URL) {
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch {
print(error)
}
}
}
Then in PlayerViewController as the playing scene. I put player.delegate = self
.
And put delegate method in below. I debug and found audioPlayerDidFinishPlaying
is not get called.
class PlayerViewController: UIViewController, AVAudioPlayerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
AudioPlayer.shared.player?.delegate = self
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
print("EAT")
goNextTrack()
} else {
fatalError("the audio doesn't finished playing successfully.")
}
}
}
Upvotes: 1
Views: 538
Reputation: 100503
May be this before you call play
it as
AudioPlayer.shared.player?.delegate = self // here player is nil and delegate won't work
AudioPlayer.shared.play(url:////)
is not same as
AudioPlayer.shared.play(url:////)
AudioPlayer.shared.player?.delegate = self // here player has a value and delegate will work
Upvotes: 3