13

Hi developers and experts, I need your good suggestions and help. I am working an application which has four different radio channels(buttons). I am using AVPlayer for live streaming. I would like to create an AVPlayer object in ViewDidLoad and just change the streaming url by using the four different buttons without having to re-create the AVPlayer object again and again. I googled but not find any solution. So your good suggestions and help would be appreciated. Thanks

- (IBAction)playBtn_clicked:(id)sender {

     NSURL *streamURL = [NSURL URLWithString:urlString];

    // I don't like this line, creating a new object again and again
    _streamPlayer = [[AVPlayer alloc] initWithURL:streamURL]; 

    if (_streamPlayer.rate == 1.0) {
        [_streamPlayer pause];
    } else {
        [_streamPlayer play];
    }
}
Gary Makin
  • 3,109
  • 1
  • 19
  • 27
Nisar Ahmad
  • 885
  • 1
  • 10
  • 25

2 Answers2

26

AVPlayer has a method to change the "currentItem" to the new one.

On ViewDidLoad()

let player = AVPlayer(playerItem: nil) // You can use an item if you have one

Then, when you want to change the current item... Or set nil to remove it...

player.replaceCurrentItem(with: AVPlayerItem(url: streamingURL))

NOTE: Yeah, it's in Swift 3, I don't have it's ObjC version at hand.

This way, you can create one single instance of AVPlayer, and handle the current AVPlayerItem being played.

Esteban Vallejo
  • 697
  • 1
  • 5
  • 11
11

Finally i found the solution by replacing the current item in AVPlayer instead of changing the Streaming URL in the Player.

 - (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view.

   _streamPlayer = [[AVPlayer alloc] init];
}


- (IBAction)playBtn_clicked:(id)sender {

  NSURL *streamURL = [NSURL URLWithString:_urlString];
  AVPlayerItem *currentItem = [[AVPlayerItem alloc] initWithURL:streamURL];
  [_streamPlayer replaceCurrentItemWithPlayerItem:currentItem];
}
Nisar Ahmad
  • 885
  • 1
  • 10
  • 25
  • 1
    I'm glad you found the solution, but that's exactly what I've pointed on my comment above (except that mines was in Swift 3). So, if you think my comment helped you, it would be good to mark it as the correct answer. Have a nice coding day! – Esteban Vallejo Jun 05 '17 at 14:16