iOS有一个类MPMoviePlayer可以用来实现视频的播放,但是用这个类不能对视频播放器对样式和功能做自定义。所以用AVplayer类来做自定义的视频播放器。
视频是在一个view上显示的,我自定义了一个View,基于UIView
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface VideoPlayerView : UIView
@property(nonatomic,retain)AVPlayer *player;
@property(nonatomic,assign)float volume;
@property (nonatomic,assign)id delegate;
@end
#import "VideoPlayerView.h"
@implementation VideoPlayerView
@synthesize volume;
@synthesize delegate;
+(Class)layerClass{
return [AVPlayerLayerclass];
}
-(AVPlayer*)player{
return [(AVPlayerLayer*)[selflayer]player];
}
-(void)setPlayer:(AVPlayer *)thePlayer{
return [(AVPlayerLayer*)[selflayer]setPlayer:thePlayer];
}
进入视频播放器时,我做的传入的视频资料是一个ALAsset类的对象指针:ALAsset * asset。
ALAssetRepresentation *defaultRepresentation = [assetdefaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *URL = [[assetvalueForProperty:ALAssetPropertyURLs]valueForKey:uti];
AVURLAsset *ass = [AVURLAssetURLAssetWithURL:URLoptions:nil];
AVPlayerItem *playerItem = [AVPlayerItemplayerItemWithURL: ass.URL];
AVPlayer *player = [AVPlayerplayerWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayerplayerLayerWithPlayer:_videoView.player];
playerLayer.videoGravity =AVLayerVideoGravityResizeAspectFill;
然后用这个对象找到对应的playerItem,然后定义一个AVPlayer用来实现视频播放等功能。
[_videoView setPlayer:player];
[_videoView.playerplay];这就开始播放视频了。
然后就是视频播放器的一些基本功能的实现:
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(moviePlayDidEnd:)name:AVPlayerItemDidPlayToEndTimeNotificationobject:_videoView.player.currentItem];
注册信号,视频播放完成的通知。视频播放完毕后在 moviePlayDidEnd回调函数中做相关处理。
_playbackProgressTimer = [NSTimerscheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(updateProgress:)
userInfo:nil
repeats:YES];
1秒触发一次的定时器,用来更新进度条。
- (IBAction)onBtnSpeedUp:(id)sender {
if (isPlaying) {
[_videoView.playerpause];
}
CMTime currentTime =_videoView.player.currentItem.currentTime;
currentDuration = (CGFloat)currentTime.value/currentTime.timescale;
CGFloat newTime = currentDuration +SPEED_UP_TIME;
if (newTime >= totalMovieDuration)
{
newTime = totalMovieDuration;
[_remoteSpeedTimerinvalidate];
_remoteSpeedTimer =nil;
}
CMTime dragedCMTime = CMTimeMake(newTime, 1);
[_videoView.playerseekToTime:dragedCMTimecompletionHandler:
^(BOOL finish)
{
if (isPlaying) {
[_videoView.playerplay];
}
}];
}
快进的实现,快退同理。
- (NSString *) getMovieTotalTime : (AVPlayerItem *)playerItem {
CMTime totalTime = [[playerItem asset] duration];
totalMovieDuration = (CGFloat)totalTime.value/totalTime.timescale;
NSDate *d = [NSDatedateWithTimeIntervalSince1970:totalMovieDuration];
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
if (totalMovieDuration/3600 >=1) {
[formatter setDateFormat:@"HH:mm:ss"];
}
else
{
[formatter setDateFormat:@"mm:ss"];
}
NSString *showtimeNew = [formatter stringFromDate:d];
return showtimeNew;
}
获取视频的时长