简体   繁体   中英

Not able to play video file on iPad using AVPlayerViewController

I have seen exactly the same issue here but its unanswered so asking the same question again. AVPlayer wont play video from url in iOS9 I tried all various ways to try to play the video but unfortunately they are not working for me. Here is the code :

AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];

NSString *url = [[NSBundle mainBundle] pathForResource:@"Intro" ofType:@"mp4"];

_asset = [AVURLAsset assetWithURL: [NSURL URLWithString:url]];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
_player = [[AVPlayer alloc] initWithPlayerItem: _playerItem];
[playerViewController.view setFrame:_videoView.frame];

playerViewController.showsPlaybackControls = YES;

[_videoView addSubview:playerViewController.view];
playerViewController.player = _player;
[_player play];

and here is the screen shot of what it looks like currently by using above code. And I used another Apple code to check the video and it worked fine but the Apple code is like too much for me as its too complicated for simple things. Here it is : https://developer.apple.com/library/prerelease/ios/samplecode/AVFoundationSimplePlayer-iOS/

在此处输入图片说明 Thanks AJ

I was finally able to figure this out by again looking into Apple's Sample code. Solution: Added the AAPLPlayerView files to my project. Then changed my UIView in Storyboard to above class Then updated below lines of code into my view controller class:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.playerView.playerLayer.player = self.player;

    NSURL *movieURL = [[NSBundle mainBundle] URLForResource:@"Intro" withExtension:@"mp4"];
    self.asset = [AVURLAsset assetWithURL:movieURL];

    self.playerItem = [AVPlayerItem playerItemWithAsset: self.asset];
    [self.player play];
}

- (AVPlayer *)player {
    if (!_player)
        _player = [[AVPlayer alloc] init];
    return _player;
}
- (AVPlayerLayer *)playerLayer {
    return self.playerView.playerLayer;
}

- (AVPlayerItem *)playerItem {
    return _playerItem;
}
- (void)setPlayerItem:(AVPlayerItem *)newPlayerItem {
    if (_playerItem != newPlayerItem) {

        _playerItem = newPlayerItem;

        // If needed, configure player item here before associating it with a player
        // (example: adding outputs, setting text style rules, selecting media options)
        [self.player replaceCurrentItemWithPlayerItem:_playerItem];
    }
}

And it worked. The issue was the PlayerLayer was not set properly and the video was not visible due to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM