How do I change the URL of AVPlayer Live Streaming?

Hi developers and experts, I need your good suggestions and help. I am working with an application that 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 with four different buttons without re-creating the AVPlayer object over and over again. I googled but couldn't find any solution. Therefore, your good suggestions and help would be appreciated. Thanks to

- (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];
    }
}

      

+3


source to share


2 answers


Finally, I found a solution by replacing the current item in the 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];
}

      

+3


source


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

In ViewDidLoad ()

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

      

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



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

      

NOTE: Yes, this is in Swift 3, I don't have the ObjC version.

This way you can create one instance of AVPlayer and handle the currently playing AVPlayerItem.

+6


source







All Articles