2

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?)
halfer
  • 19,824
  • 17
  • 99
  • 186
Dmitriy Kalachniuk
  • 372
  • 1
  • 6
  • 25

2 Answers2

6

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 #> 
 }];
djromero
  • 19,551
  • 4
  • 71
  • 68
  • 1
    +1 Much better to use the periodicTimeObserver than introducing yet another polling timer. – Till Jan 13 '12 at 00:05
3

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
Community
  • 1
  • 1
Alex
  • 2,468
  • 1
  • 20
  • 16
  • 1
    I tried to to exactly this in background. But the new AVPlayer object does not start playing when in background. How did you deal with that? – V1ru8 Mar 08 '12 at 13:46
  • What you mean when you say in a "background"? – Alex Mar 08 '12 at 21:53