ios - AVPlayer 不会播放不同的格式

标签 ios singleton avplayer

我正在使用 AVPlayer 实现播放器,它将播放来自 URL 的视频。此 URL 可以用于“固定长度”视频(具有预定持续时间)和直播视频(持续时间未知/未定义)。

我使用的固定长度 URL 链接到 .mp4 文件(使用 H264 编解码器),而实时视频具有 .m3u8 扩展名(但也是 H264)。

我可以播放许多 .m3u8 URL,但是当我尝试播放 .mp4 时,它不会加载。 但是,如果我启动应用程序并先播放一个 .mp4 网址,我可以播放其他 .mp4 网址,但我无法切换到 .m3u8。
两种格式都可以正常播放,但是当我从一种格式切换到另一种格式时会出现一些问题。

这些是我用来实例化和“清理”播放器的方法:

- (void)prepareAndPlayAutomatically:(BOOL)playAutomatically {
  currentItem = [AVPlayerItem playerItemWithURL:videoURL];
  [[self player] replaceCurrentItemWithPlayerItem:currentItem];
  [self.layer addSublayer:[self playerLayer]];

  [[self player] addObserver:self forKeyPath:@"rate" options:0 context:nil];

  [[self player] seekToTime:kCMTimeZero];

  if (playAutomatically) {
    [[self player] play];
  }
}

- (void)clean {
  [[self player] pause];
  [[self player] seekToTime:kCMTimeZero];
  [[self player] replaceCurrentItemWithPlayerItem:nil];
  [[self player] removeObserver:self forKeyPath:@"rate"];
  [self removeFromSuperview];
}

[self player] 将返回一个单例 AVPlayer 实例;
[self playerLayer] 也会返回一个单独的 AVPlayerLayer 实例;

- (AVPlayer *)player {
  static dispatch_once_t once;
  static AVPlayer *player;
  dispatch_once(&once, ^{
    player = [AVPlayer playerWithPlayerItem:currentItem];
  });
  return player;
}

- (AVPlayerLayer *)playerLayer {
  static dispatch_once_t once;
  static AVPlayerLayer *playerLayer;
  dispatch_once(&once, ^{
    playerLayer = [AVPlayerLayer playerLayerWithPlayer:[self player]];
  });
  return playerLayer;
}

我已将问题缩小到这些单例。如果我去掉单例模式,就不会出现问题,而且我可以播放两种视频。

“清理”播放器时我还应该做些什么吗?

最佳答案

似乎 AVPlayer 类不适用于具有不同视频组成的项目。

来自 [AVPlayer replaceCurrentItemWithPlayerItem:] method 上的文档:

Special Considerations

The new item must have the same compositor as the item it replaces, or have no compositor.

关于ios - AVPlayer 不会播放不同的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27429887/

相关文章:

objective-c - 几个TableView问题

C# 单元测试 : How do I set a Lazy<T>. ValueCreated 为假?

c# - 单例和 HttpApplicationState

ios - 如何用AVPlayer解析m3u文件

macos - setAspectRatio 在调整窗口大小之前不起作用

ios - 在 APNS 中,无法在除 iPhone 4 以外的任何设备中获取设备 token

ios - 解析后端 : key won't increment?

Xcode 4.5 中的 iOS 代码覆盖率被破坏了吗?

C# WPF 如何强制执行 Windows 的单个实例

ios - 从远程 URL 下载视频到设备并通过 AVPlayer 流式传输