1

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)
    }
Björn
  • 111
  • 10

1 Answers1

1

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()
    }
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • Just found time to try this. It works, thank you so much! One more question though: I need to have a different pause for different audio items in my queue. How do I pass a variable to this function? – Björn Aug 31 '19 at 22:45
  • also, figured out to use `wallDeadline` instead of `deadline` if the counter should work while phone in sleep – Björn Sep 01 '19 at 16:47
  • 1
    Turns out this does not work with Bluetooth headphones. It's always cutting out a couple of milliseconds when the next item resumes playback. Any idea how I could solve that? – Björn Sep 03 '19 at 03:02
  • ...I'm just going to hack this by inserting audio files with silence in order to create pauses in between items – Björn Sep 03 '19 at 03:44