如何更改AVPlayer Live Streaming URL?

Nis*_*mad 6 objective-c audio-streaming live-streaming ios avplayer

嗨开发人员和专家,我需要你的好建议和帮助.我正在使用一个具有四个不同无线电频道(按钮)的应用程序.我正在使用AVPlayer进行直播.我想在ViewDidLoad中创建一个AVPlayer对象,只需使用四个不同的按钮更改流式URL,而无需一次又一次地重新创建AVPlayer对象.我用Google搜索但没有找到任何解决方案.所以你的好建议和帮助将不胜感激.谢谢

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

Est*_*ejo 13

AVPlayer有一种方法可以将"currentItem"更改为新的.

在ViewDidLoad()上

let player = AVPlayer(playerItem: nil) // You can use an item if you have one
Run Code Online (Sandbox Code Playgroud)

然后,当你想要改变当前项目时...或者设置为nil以删除它...

player.replaceCurrentItem(with: AVPlayerItem(url: streamingURL))
Run Code Online (Sandbox Code Playgroud)

注意:是的,它在Swift 3中,我没有它的ObjC版本.

这样,您可以创建一个AVPlayer实例,并处理正在播放的当前AVPlayerItem.

  • ObjC: [玩家替换CurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:streamingURL]]; (2认同)

Nis*_*mad 5

最后,我找到了解决方案,方法是替换AVPlayer中的当前项目,而不是更改Player中的Streaming URL。

 - (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];
}
Run Code Online (Sandbox Code Playgroud)