Why this Objective-C code won't play an AVPlayerViewController video?

走远了吗. 提交于 2019-11-30 16:11:39
@import AVKit;
@import AVFoundation;
@property (nonatomic) AVPlayer *avPlayer; 
@property (nonatomic) AVPlayerViewController* avPlayerView;


NSString *path = [[NSBundle mainBundle] pathForResource:@"Video1" ofType:@"mp4"];

NSURL *url = [[NSURL alloc] initFileURLWithPath: path];

AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];

avPlayer = [AVPlayer playerWithPlayerItem:anItem];
[avPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
self.avPlayerView = [[AVPlayerViewController alloc] init];
self.avPlayerView.view.frame = self.view.bounds; 
[self.avPlayerView setPlayer:_avPlayer]; 
[self.view addSubview:_avPlayerView.view]; 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == avPlayer && [keyPath isEqualToString:@"status"]) {
        if (avPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");
        } else if (avPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayer Ready to Play");
        } else if (avPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");
        }
    }
}

-(IBAction) BtnPlay:(id)sender {
    [avPlayer play];
}

-(IBAction) BtnPause:(id)sender {
    [avPlayer pause];
}

Try my code . if any issue with my code put comment . Thank You. Happy Coding.

NSString *path = [[NSBundle mainBundle] pathForResource:@"charlie" ofType:@"mp4"];

Try

Using [NSURL fileURLWithPath:path] instead of [NSURL URLWithString:path]

[NSURL fileURLWithPath]

Or

[[NSBundle mainBundle] URLForResource:@"charlie" withExtension:@"mp4"]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!