iosobjective-ciphoneavfoundationavplayer

Check play state of AVPlayer


Is there a way to know whether an AVPlayer playback has stalled or reached the end?


Solution

  • To get notification for reaching the end of an item (via Apple):

    [[NSNotificationCenter defaultCenter] 
          addObserver:<self>
          selector:@selector(<#The selector name#>)
          name:AVPlayerItemDidPlayToEndTimeNotification 
          object:<#A player item#>];
    

    And to track playing you can:

    "track changes in the position of the playhead in an AVPlayer object" by using addPeriodicTimeObserverForInterval:queue:usingBlock: or addBoundaryTimeObserverForTimes:queue:usingBlock:.

    Example is from Apple:

    // Assume a property: @property (retain) id playerObserver;
    
    Float64 durationSeconds = CMTimeGetSeconds([<#An asset#> duration]);
    CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 1);
    CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 1);
    NSArray *times = [NSArray arrayWithObjects:[NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird], nil];
    
    self.playerObserver = [<#A player#> addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
        // Passing NULL for the queue specifies the main queue.
    
        NSString *timeDescription = (NSString *)CMTimeCopyDescription(NULL, [self.player currentTime]);
        NSLog(@"Passed a boundary at %@", timeDescription);
        [timeDescription release];
    }];