2017-09-20 38 views
0

當我第一次播放任何視頻時,視頻播放完全正常,但是當我從手機的媒體庫中選擇視頻並替換它時,視頻在2秒後變黑且音頻播放至結束。 添加視頻播放器在這裏:更換AVPlayerItem後數秒後視頻變黑

-(void) addMoviePlayer{ 
NSString *path = [[NSBundle mainBundle] pathForResource:@"got1" ofType:@"mp4"]; 
NSURL *videoURL = [NSURL fileURLWithPath:path]; 

AVAsset *asset = [AVAsset assetWithURL:videoURL]; 
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset]; 
AVPlayer *vidPlayer = [[AVPlayer alloc] initWithPlayerItem:item]; 
CGRect vidRect = CGRectMake(0, self.view.bounds.size.height * 0.15, self.view.bounds.size.width, self.view.bounds.size.height * 0.3); 

videoLayer = [AVPlayerLayer layer]; 
[videoLayer setPlayer:vidPlayer]; 
[videoLayer setBackgroundColor:[UIColor clearColor].CGColor]; 
[videoLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; 
videoLayer.frame = vidRect; 
[self.view.layer addSublayer:videoLayer]; 
vidPlayer.muted = true; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:vidPlayer.currentItem]; 
} 

然後我更換AVPlayerItem與一個從畫廊挑選。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; 
NSLog(@"VideoURL = %@", videoURL); 

[picker dismissViewControllerAnimated:YES completion:^{ 
    AVPlayerItem *currentItem = [[AVPlayerItem alloc] initWithURL:videoURL]; 
    [videoLayer.player replaceCurrentItemWithPlayerItem:currentItem]; 
    [videoLayer.player play]; 
}]; 

回答

0

希望這會對你有幫助。

-(void)playVideoFile:(NSURL *)fileUrl{ 

AVPlayer *videoPlayer = [[AVPlayer alloc] initWithURL:fileUrl]; 
AVPlayerViewController *videoController = [AVPlayerViewController new]; 
videoController.player = videoPlayer; 

[self presentViewController:videoController animated:YES completion:nil];} 
+0

請先通過我的問題。這當然不是我所要求的。 –