No AVPlayer Delegate? How to track when song finished playing? Objective C iPhone development

63,213

Solution 1

Yes, the AVPlayer class does not have a delegate protocol like the AVAudioPlayer. You need to subscribe to notifications on an AVPlayerItem. You can create an AVPlayerItem using the same URL that you would otherwise pass to -initWithURL: on AVPlayer.

-(void)startPlaybackForItemWithURL:(NSURL*)url {

    // First create an AVPlayerItem
    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:url];

    // Subscribe to the AVPlayerItem's DidPlayToEndTime notification.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

    // Pass the AVPlayerItem to a new player
    AVPlayer* player = [[[AVPlayer alloc] initWithPlayerItem:playerItem] autorelease];

    // Begin playback
    [player play]

} 

-(void)itemDidFinishPlaying:(NSNotification *) notification {
    // Will be called when AVPlayer finishes playing playerItem
}

Solution 2

Yes. Add a KVO observer to the player's status or rate:

- (IBAction)go {
   self.player = .....
   self.player.actionAtItemEnd = AVPlayerActionStop;
   [self.player addObserver:self forKeyPath:@"rate" options:0 context:0]; 
}

- (void)stopped {
    ...
    [self.player removeObserver:self]; //assumes we are the only observer
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == 0) {
        if(player.rate==0.0) //stopped
            [self stopped];
    }
    else
        [super observeVal...];
}

So basically, that's it.

Disclaimer: I wrote that in here so I didn't check if the code was good. ALSO I never used AVPlayer before but it should be about right.

Solution 3

Swift 3 - I add an observer to AVPlayerItem every time I add a video to the player:

func playVideo(url: URL) {
  let playerItem = AVPlayerItem(asset: AVURLAsset(url: someVideoUrl))
  NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
  self.player.replaceCurrentItem(with: playerItem)
  self.player.play()
}

func playerItemDidPlayToEndTime() {
  // load next video or something
}

Solution 4

There is a lot of information in the Apple docs AVFoundation Programming Guide (look for the monitoring playback section). It appears to be mainly through KVO so you may wish to brush up on that if you are not too familiar (there is a guide for that to Key Value Observing ProgrammingGuide.

Solution 5

I'm using this one, and it works:

_player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:_playingAudio.url]];
CMTime endTime = CMTimeMakeWithSeconds(_playingAudio.duration, 1);
timeObserver = [_player addBoundaryTimeObserverForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:endTime]] queue:NULL usingBlock:^(void) {
    [_player removeTimeObserver:timeObserver];
    timeObserver = nil;
    //TODO play next sound
}];
[self play];

where _playingAudio is my custom class with some properties and timeObserver is id ivar.

Share:
63,213
Tyler
Author by

Tyler

Updated on April 28, 2020

Comments

  • Tyler
    Tyler about 4 years

    I've looked around but I can't find a delegate protocol for the AVPlayer class. What gives?

    I'm using its subclass, AVQueuePlayer, to play an array of AVPlayerItems, each loaded from a URL. Is there any way I can call a method when a song finishes playing? Notably at the end of the queue?

    And if that's not possible, is there any way I could call a method when the song STARTS playing, after buffering? I'm trying to get a loading icon in there but it turns the icon off before the music actually begins, even though it's after the [audioPlayer play] action.

  • Tyler
    Tyler almost 13 years
    Thanks, first I got it working by monitoring the time through KVO but then I implemented the AVPlayerItemDidPlayToEndTimeNotification since it's cleaner and less processor-intensive.
  • Rudolf Adamkovič
    Rudolf Adamkovič over 10 years
    Be sure to use itemDidFinishPlaying:, e.g. with colon. From NSNotificationCenter documentation: The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).
  • arexx
    arexx over 10 years
    @RudolfAdamkovic Thanks for the note - I've edited my answer accordingly.
  • Saumil Shah
    Saumil Shah about 8 years
    How to remove @"rate" observer?
  • Daij-Djan
    Daij-Djan over 7 years
    I was told in an edit that I need to observe rate for sure. adapted
  • CupawnTae
    CupawnTae almost 7 years
    A bit of a crazy mix of NSNotificationCenter, KVO and block-based in there. Make your mind up Apple!
  • C6Silver
    C6Silver over 6 years
    A problem with this approach is that it will think a pause is the end of the music. Rate at pause is zero as it would be at end.