2

在我的 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 并在完成工作后将其设置为零。这个问题可能是什么原因,我该如何解决这个问题?

4

1 回答 1

2

将评论中的 Bhavesh Lathigara 解决方案移至社区 Wiki 答案:

调用时didReceiveMemoryWarning,将所有与视频/音频播放相关的对象清零,并在需要时重新创建它们。

于 2016-04-22T15:11:23.940 回答