Search code examples
iphoneavfoundationuislideravplayer

Should I stop current AVPlayer instance when playing music from another URL?


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?)

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