iOS开发交流群:301058503
Demo地址:https://github.com/liumude/MediaPlay.git
(自己封装的,写得不好还请指出)
- 新建一个继承NSObject的类PlayModel
- 导入音视频播放需要的头文件
#import <Foundation/Foundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
3.创建播放单例
+(PlayModel *)shareInstance{
static PlayModel *player = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
player = [[PlayModel alloc] init];
});
return player;
}
4.音频播放初始化
//音频
-(void)initAudioPlayerWithUrl:(NSURL *)url{
playerItem = [AVPlayerItem playerItemWithURL:url];
audioPlayer =[AVPlayer playerWithPlayerItem:playerItem];
[self start];
currentTime = 0;
// //支持后台播放 还要在background modes 勾选Audio,AirPlay
// AVAudioSession *session = [AVAudioSession sharedInstance];
// [session setActive:YES error:nil];
// [session setCategory:AVAudioSessionCategoryPlayback error:nil];
}
5.视频播放初始化
//视频
-(void)initMoviePlayerWithUrl:(NSURL *)url addToView:(UIView *)view{
playerItem = [AVPlayerItem playerItemWithURL:url];
audioPlayer =[[AVPlayer alloc] initWithPlayerItem:playerItem];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:audioPlayer];
playerLayer.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);
[view.layer addSublayer:playerLayer];
playerLayer.videoGravity =AVLayerVideoGravityResizeAspect;
currentTime = 0;
}
6.开始播放的方法
-(void)start{
[audioPlayer play];
if(_timer != nil){
[_timer invalidate];
_timer = nil;
}
//获取播放进度
_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
//播放开始的通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PlayStart" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playStart:) name:@"PlayStart" object:nil];
//播放结束的通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"PlayEnd" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:@"PlayEnd" object:nil];
}
7.获取当前时间和总时间
-(CGFloat)currentTime{
return CMTimeGetSeconds(playerItem.currentTime);
}
-(CGFloat)duration{
return CMTimeGetSeconds(playerItem.duration);
}
8.播放进度
-(void)progressAction{
if(currentTime < [self currentTime]){//当前时间比播放前的时间大,播放开始
[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayStart" object:nil userInfo:nil];
}
if([self currentTime] >= [self duration]){//播放结束
[[NSNotificationCenter defaultCenter] postNotificationName:@"PlayEnd" object:nil userInfo:nil];
}
if(_isplaying){
if(_playDelegate != nil){
[_playDelegate playingProgress:[self currentTime]/[self duration]];
}
}
}
9.从特定时间开始播放
//从特定时间开始播放
-(void)playWithTime:(CGFloat)time{
[self pause];
CMTime pointTime = CMTimeMake(time * [self duration], 1);
currentTime = time * [self duration];//获取播放前的当前时间
[playerItem seekToTime:pointTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[self start];
}
以上是主要代码,详细请看Demo:https://github.com/liumude/MediaPlay.git
iOS开发交流群:301058503