2015-07-10 168 views
1

我想在我的視圖中播放循環背景視頻。我寫了這個代碼:背景視頻Objective-c

-(AVPlayerLayer*)playerLayer{ 

    if(!_playerLayer){ 

    // find movie file 
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"fond_login" ofType:@"mp4"]; 
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath]; 
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:[[AVPlayer alloc]initWithURL:movieURL]]; 
    _playerLayer.frame = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height); 
    [_playerLayer.player play]; 
    return _playerLayer; 
} 
return nil; } 

-(void)replayMovie:(NSNotification *)notification { 
NSLog(@"Finis"); 
[self.playerLayer.player play];} 

在我viewDidLoad中,我有:

[self.view.layer addSublayer:self.playerLayer]; 
[[NSNotificationCenter defaultCenter] addObserver: self 
             selector: @selector(replayMovie:) 
              name: AVPlayerItemDidPlayToEndTimeNotification 
              object:nil]; 

我的問題是,視頻不循環播放。我一次看到視頻並完成。我不知道爲什麼..

感謝的

編輯:

我看到另一個教程。

@import MediaPlayer; 

@property (nonatomic, strong) MPMoviePlayerController *moviePlayer; 

我在viewDidLoad中代碼:

NSURL *videoURL = [[NSBundle mainBundle] URLForResource:@"my_video" withExtension:@"format"]; 

self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL]; 
self.moviePlayer.controlStyle = MPMovieControlStyleNone; 
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFill; 
self.moviePlayer.view.frame = self.view.frame;[self.view insertSubview:self.moviePlayer.view atIndex:0]; 
[self.moviePlayer play]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loopVideo) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer]; 

和:

- (void)loopVideo { 
[self.moviePlayer play]; } 

它的工作完美。

+0

你有沒有看到你的replayMovie事件火災? – Dan

+0

沒有replayMovie被稱爲.. –

回答

0

在你replayMovie:方法,你需要尋求回到開頭:

- (void)replayMovie:(NSNotification *)notification { 
    [(AVPlayerItem *)notification.object seekToTime:kCMTimeZero]; 
} 

您還打算要設置的AVPlayeractionAtItemEnd因此不會暫停:

_playerLayer.player.actionAtItemEnd = AVPlayerActionAtItemEndNone; 
+0

感謝您的回答! –