ios上的AVPlayer Objective C app不播放视频

时间:2017-11-30 00:28:43

标签: ios objective-c avplayer xib

您好我有一个iOS Objective-C应用程序,它不使用Storyboard(它使用XIB文件)

我想添加一个启动画面来播放视频,所以我添加了一个从UIViewController派生的新Coca Touch类(并勾选'也创建XIB文件)。

我已将此课程换成我的新主屏幕并且正确加载但不播放视频。我添加了AVFoundation框架等,这不是问题。

这是我的代码。

.h文件

#import <UIKit/UIKit.h>

@interface VideoIntroViewController : UIViewController
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end

.m文件

import <AVFoundation/AVFoundation.h>

static const float PLAYER_VOLUME = 0.0;

@interface VideoIntroViewController ()

@property (nonatomic) AVPlayer *player;
@property (weak, nonatomic) IBOutlet UIView *playerView;

@end

@implementation VideoIntroViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createVideoPlayer];
}

- (void)createVideoPlayer
 {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];

    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    self.player.volume = PLAYER_VOLUME;

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.videoGravity = UIViewContentModeScaleToFill;
    playerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:playerLayer];

    [self.player play];
}

屏幕已启动,但没有视频播放。

可能出现什么问题?

2 个答案:

答案 0 :(得分:1)

试试这段代码:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"welcome_video" ofType:@"mp4"];
NSURL *url = [NSURL fileURLWithPath:filePath];

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];

CALayer *superlayer = self.playerView.layer;
self.player.volume = 1.0;

AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;// you can also use AVLayerVideoGravityResizeAspect to clip video to view's bound
playerLayer.frame = self.playerView.layer.bounds;

[superlayer addSublayer:playerLayer];
[self.player seekToTime:kCMTimeZero];
[self.player play];

我已经检查了其他视频文件,但它运行正常。

答案 1 :(得分:0)

在我的主XIB文件中,我没有放置View控件。 当我放置一个视图控件,然后CTL +右键单击并将其连接到我的播放器后,然后播放视频。