Question

I just created AVPlayer and it plays music well. I have two questions

  1. How to play another music from another URL (should I stop current player?)
  2. How to show current time of the song in UISlider (actually is it a method that called when the song is playing?)
Was it helpful?

Solution

1) If you used - (id)initWithURL:(NSURL *)URL then you should stop player with pause, dealloc it and create new instance.

    AVPlayer *player = [AVPlayer alloc] initWithURL:[NSURL URLWithString:@"http:/someurl.com"]];
    [player play];
    [player pause];
    [player release];

    player = [AVPlayer alloc] initWithURL:[NSURL URLWithString:@"http:/someurl2.com"]];
    [player pause];
    [player release];

If you used playerWithURL, then just call the same line again.

2). The easiest is the get duration of the current item https://stackoverflow.com/a/3999238/619434 and then update the UISlider with that value. You can use NSTimer to periodically check the duration.

      self.player.currentItem.asset.duration

OTHER TIPS

Use -[AVPlayer replaceCurrentItemWithPlayerItem] to replace the current playing item reusing the player instance. You can create an item with an URL or with an asset.

In order to know when a given item finishes playing use the notification AVPlayerItemDidPlayToEndTimeNotification.

Use -[AVPlayer addPeriodicTimeObserverForInterval] to perform some action periodically while the player is playing. See this example:

[self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1, 100) 
                                          queue:nil 
                                     usingBlock:^(CMTime time) { 
                                     <# your code will be called each 1/10th second #> 
 }];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top