嗨,我有一个iOS Objective-C应用程序,它不使用Storyboards(它使用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];
}
屏幕已启动,但没有视频播放。
怎么可能出错?
试试这段代码:
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];
我检查了一些其他视频文件,它工作正常。
在我的主XIB文件中,我没有放置View控件。当我放置一个视图控件,然后CTL +右键单击并将其连接到我的播放器后,然后播放视频。