音频播放使用的是AVFoundation框架的AVPlayer,使用通知监听播放结束,使用系统的addPeriodicTimeObserverForInterval监听播放进度,当播放进度开始时开始回调,主要是解决监听播放开始不准确的问题,在使用结束时调用dm_removeNoticAndObsever方法,把通知和kvo清除
代码如下
//
// DM_SoundManager.h
// Video2
//
// Created by 魏友臣 on 2019/1/21.
// Copyright © 2019 魏友臣. All rights reserved.
//
#import
#import
@class DM_SoundManager;
@protocolDM_SoundManagerDelagete
/**
播放结束
*/
- (void)dm_soundManagerDidEnd:(DM_SoundManager*)DM_SoundManager;
/**
播放进度 0.1s
*/
- (void)dm_soundManager:(DM_SoundManager*)DM_SoundManager plyerProgress:(double)progress;
@end
@interfaceDM_SoundManager :NSObject
@property(nonatomic,weak)id<DM_SoundManagerDelagete>delegate;
-(instancetype)initWithUrl:(NSURL*)url delegate:(id)delegate;
- (void)dm_removeNoticAndObsever;
@end
//
// DM_SoundManager.m
// Video2
//
// Created by 魏友臣 on 2019/1/21.
// Copyright © 2019 魏友臣. All rights reserved.
//
#import "DM_SoundManager.h"
@implementationDM_SoundManager
{
AVPlayer*_soundPlay;
id_timeObserver;
BOOLisClear;
}
-(instancetype)initWithUrl:(NSURL*)url delegate:(id)delegate{
if(self= [superinit]) {
[selfsetPlayerUrl:urldelegate:delegate];
}
return self;
}
- (void)setPlayerUrl:(NSURL*)url delegate:(id)delegate{
self.delegate= delegate;
_soundPlay = [[AVPlayer alloc]initWithURL:url];
[_soundPlay play];
isClear=NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:_soundPlay.currentItem];
__weak typeof(self)ws = self;
_timeObserver = [_soundPlay addPeriodicTimeObserverForInterval:CMTimeMake(1,10) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
doublesec =CMTimeGetSeconds(time);
if(sec>0) {
if(ws.delegate&&@selector(dm_soundManager:plyerProgress:)) {
[ws.delegate dm_soundManager:ws plyerProgress:sec];
}
}
}];
}
- (void)playbackFinished
{
if(self.delegate&&@selector(dm_soundManagerDidEnd:)) {
[self.delegate dm_soundManagerDidEnd:self];
}
}
- (void)dm_removeNoticAndObsever
{
if(isClear==NO) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
[_soundPlay removeTimeObserver:_timeObserver];
[_soundPlaypause];
isClear=YES;
}
}
@end