ios - 使用 iOS AVPlayer 时由于内存压力而终止

标签 ios objective-c avplayer ytplayerview memory-pressure

在我的 iOS 应用程序中,我在 iOS YouTube helper library 的帮助下循环运行 YouTube 视频。 。但我没有机会完整播放该视频,但 20 秒后我再次将同一视频排队,如下所示。

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state{

    if (state == kYTPlayerStateQueued) {
        startedTimer = NO;

        [self.playerView playVideo];      
    } else if (state == kYTPlayerStatePlaying) {

        if (!startedTimer) {
            startedTimer = YES;

            vidReplayTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(restartVideo) userInfo:nil repeats:NO];
        }
    } 
}

- (void)restartVideo {
    [self.playerView cueVideoById:selectedYTVideoId startSeconds:0.1 suggestedQuality:kYTPlaybackQualityMedium];
}

这完全符合我的要求。

接下来我想在 YouTube 每次重播视频之前播放 mp4 文件。为了实现这一点,我使用了 AVPlayer 。然后代码已更改如下。

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state{

    if (state == kYTPlayerStatePlaying) {
        if (self.avPlayer != nil) {
            avPlayerLayer.hidden = YES;
            self.avPlayer = nil;
        }

        if (!startedTimer) {
            startedTimer = YES;

            vidReplayTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(restartVideo) userInfo:nil repeats:NO];
        }
    } 
}

- (void)restartVideo {
    self.avPlayer = [AVPlayer playerWithURL:introVideoFileURL];

    avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    avPlayerLayer.frame = CGRectMake(0, 0, 320, 330);
    [self.view.layer addSublayer: avPlayerLayer];

    [self.avPlayer play];

    [self.playerView cueVideoById:selectedYTVideoId startSeconds:0.1 suggestedQuality:kYTPlaybackQualityMedium];
}

经过上述更改后,应用程序按我的预期运行,但运行近四分钟后,我的 Xcode 中出现“由于内存压力而终止”弹出窗口,并且应用程序崩溃。我已经使用 Instruments 开发工具检查了内存,应用程序崩溃时已使用近 35 MB 内存。当应用程序开始运行时,它使用了超过 45 MB 的内存并且运行平稳。

如您所见,我仅在需要时创建 AVPlayer,并在完成工作后将其设置为 nil。造成此问题的原因是什么以及如何解决此问题?

最佳答案

将 Bhavesh Lathigara 的解决方案移至 comments社区 Wiki 答案:

When didReceiveMemoryWarning is called, nil all the objects that are related to video/audio playback and re-create them when needed again.

关于ios - 使用 iOS AVPlayer 时由于内存压力而终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25031269/

相关文章:

ios - 将 uitabbar 实现到 uitableview

iphone - Objective C 中的 Singleton 问题

iOS - 重置命令中心/远程播放器

objective-c - 将音频路由到 OS X 上的特定设备输出

ios - 如何仅使用位置经度和纬度从 google place api 获取地点详细信息

ios - Xcode 5.1.1 - 错误 : Start Page at 'www/index.html' was not found

ios - RoboVM 中非常奇怪的 NullPointerException

ios - 带有图像的 UITableview 滚动速度非常慢

objective-c - iOS 5 中的 setTitleView 奇怪行为 - objective-c

ios - 某些音频文件未使用 AVPlayer swift 4 播放