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

前端 未结 2 451
清歌不尽
清歌不尽 2021-01-03 10:48

Both are in viewDidLoad(). What\'s wrong with this objective-c source file? The swift version works like a charm... Xcode ver. 8.2 iOS 10

Swift (OK):



        
2条回答
  •  走了就别回头了
    2021-01-03 11:19

    @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.

提交回复
热议问题