我用_
AVMoviePlayerView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class AVPlayer;
@interface AVMoviePlayerView : UIView
@property (nonatomic) AVPlayer *player;
- (void)setPlayer:(AVPlayer*)player;
- (void)setVideoFillMode:(NSString *)fillMode;
@end
和
AVMoviePlayerView.m
#import "AVMoviePlayerView.h"
#import <CoreMedia/CoreMedia.h>
@implementation AVMoviePlayerView
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer*)player
{
return [(AVPlayerLayer*)[self layer] player];
}
- (void)setPlayer:(AVPlayer*)player
{
[(AVPlayerLayer*)[self layer] setPlayer:player];
}
- (void)setVideoFillMode:(NSString *)fillMode
{
AVPlayerLayer *playerLayer = (AVPlayerLayer*)[self layer];
playerLayer.videoGravity = fillMode;
}
@end
从我的 MainViewController.m 内部调用它 -(void)viewDidLoad
NSURL* url = [[NSBundle mainBundle] URLForResource:@"myVideo.264" withExtension:@"mp4"];
self.avPlayer = [AVPlayer playerWithURL:url];
[avPlayer addObserver:self forKeyPath:@"status" options:0 context:AVMoviePlayerViewControllerStatusObservationContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.avPlayer currentItem]];
用方法
- (void)observeValueForKeyPath:(NSString*) path ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if (avPlayer.status == AVPlayerStatusReadyToPlay) {
[self.VideoLoop setPlayer:self.avPlayer];
[self.avPlayer play];
}
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}
当然在 MainViewController.h 中定义
...
#import <CoreGraphics/CoreGraphics.h>
#import "AVMoviePlayerView.h"
@class AVMoviePlayerView;
@class AVPlayer;
...
IBOutlet AVMoviePlayerView *VideoLoop;
AVPlayer* avPlayer;
它在模拟器中工作正常(循环除外,但这是一个不同的问题),但在设备(iPad3)上没有视频显示。
我错过了什么吗?谢谢!!!