OGeek|极客世界-中国程序员成长平台

标题: ios - AVPlayer 在后台 View Controller 中缓冲视频会导致内存问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:33
标题: ios - AVPlayer 在后台 View Controller 中缓冲视频会导致内存问题

我正在制作一个带有 AVPlayer 的 View Controller 的直播电视流媒体应用。

- (void)viewDidLoad {
    self.playerViewController = [[AVPlayerViewController alloc] init];
    self.playerViewController.player = [AVPlayer playerWithURL:[NSURL URLWithString:StreamURL]];
    [self addChildViewController:self.playerViewController];
    [self.view addSubview:self.playerViewController.view];
    [self.playerViewController.player play];
}

我还有一个按钮,它显示一个带有附加信息的新 View Controller 。当我展示新的 View Controller 时, AVPlayer 会继续播放音频,这就是我想要的。

问题是 - 当我展示新的 View Controller 时,AVPlayer 在后台播放音频但继续缓冲视频,当 View Controller 被关闭时,AVPlayer 快进视频,以便它可以与音频同步。快速转发导致内存使用量大幅增加,并且我收到内存不足警告。新 View Controller 在前台的时间越长,当我关闭它时,内存跳跃就越大。

如何阻止 AVPlayer 缓冲视频?



Best Answer-推荐答案


我可能会迟到一点,但如果有人对此仍有疑问,我可以建议减少进入后台时的播放器缓冲区。我知道这不是一个完美的答案,但这仍然会有所帮助。

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selectorselector(onApplicationDidEnterBackgroundNotification
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selectorselector(onApplicationWillEnterForegroundNotification
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

然后

- (void)onApplicationDidEnterBackgroundNotificationNSNotification *)notification {
    self.playerItem.preferredForwardBufferDuration = 1;
}
- (void)onApplicationWillEnterForegroundNotificationNSNotification *)notification {
    self.playerItem.preferredForwardBufferDuration = 0;
}

别忘了在 dealloc 中移除观察者

 [[NSNotificationCenter defaultCenter] removeObserver:self];

关于ios - AVPlayer 在后台 View Controller 中缓冲视频会导致内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41599605/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4