2014-04-30 109 views
0

我想在视图的框架中播放视频,但以下代码不起作用。 你能帮助我吗?AVPlayer在视图中播放库视频

MPMediaItem *song = [allVideos objectAtIndex:indexPath.row]; 
NSLog(@"%@",[song valueForProperty:MPMediaItemPropertyAssetURL]); 
NSURL *url = [song valueForProperty:MPMediaItemPropertyAssetURL]; 
AVPlayer *player = [[AVPlayer alloc] init]; 
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; 
AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:avAsset]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(playerItemDidReachEnd:) 
              name:AVPlayerItemDidPlayToEndTimeNotification 
              object:playerItem]; 
player = [[AVPlayer alloc]initWithPlayerItem:playerItem]; 

//[player seekToTime:kCMTimeZero]; 
[player play]; 
+0

您需要创建AVPlayerLayer实例,并将其添加到当前视图层次结构。 – cekisakurek

回答

1

您需要使用AVPlayerLayer,添加此

AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:player]; 
[self.view.layer addSublayer:playerLayer]; 

你的代码。

+0

它的工作原理,谢谢 – Meins

+0

欢迎您! – cekisakurek

0

你有没有尝试使用MPMoviePlayerController像下面

MPMoviePlayerController * _player = [[MPMoviePlayerController alloc] initWithContentURL:fileURL]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackComplete:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackChanged:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; 

    CGRect frame = self.frame; 

    frame.origin = CGPointZero; 

    _player.view.frame = frame; 

    [self.view addSubview:_player.view]; 

    [_player prepareToPlay]; 

    [_player play]; 
+0

我只看到黑色的视图 – Meins

0

试试这个..

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:path]]; 
player.view.frame = CGRectMake(0,45, 1024, 723); // take your require frame size of player 
[player.view setBackgroundColor:[UIColor clearColor]]; 
player.repeatMode=MPMovieRepeatModeNone; 
[self.view addSubview:player.view]; 
[player play];