I am using AVQueuePlayer to playback a batch of audio files. I'd like to insert a pause in between items. Any idea how to do that?
Here the method that adds items into the queue:
func addItemToAudioQueue (file:String, last:Bool) {
let urlPath = Bundle.main.path(forResource: file, ofType: "mp3")
let fileURL = NSURL(fileURLWithPath:urlPath!)
let playerItem = AVPlayerItem(url:fileURL as URL)
if last {
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
}
queuePlayer.insert(playerItem, after: nil)
}
Add an observer
for the notification
named AVPlayerItemDidPlayToEndTimeNotification
that will be fired every time an AVPlayerItem
is finished playing, i.e.
NotificationCenter.default.addObserver(self, selector: #selector(playerEndedPlaying), name: Notification.Name("AVPlayerItemDidPlayToEndTimeNotification"), object: nil)
AVPlayerItemDidPlayToEndTimeNotification
A notification that's posted when the item has played to its end time.
Next, when the playerEndedPlaying
method is called after the notification
is fired, pause()
the AVQueuePlayer
initially and then play()
it again after 5 seconds like so,
@objc func playerEndedPlaying(_ notification: Notification) {
self.player?.pause()
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {[weak self] in
self?.player?.play()
}
}