Search code examples
iosvideoavplayerplayback

AVPlayer play library video in view


i want to play a video in a frame of a view, but the following code does not work. can you help me?

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];

Solution

  • You need to use AVPlayerLayer, add this

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

    to your code.