DFPlayer.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. //
  2. // DFPlayer.m
  3. // DFPlayer
  4. //
  5. // Created by ihoudf on 2017/7/18.
  6. // Copyright © 2017年 ihoudf. All rights reserved.
  7. //
  8. #import "DFPlayer.h"
  9. #import "DFPlayerFileManager.h"
  10. #import "DFPlayerResourceLoader.h"
  11. #import "DFPlayerTool.h"
  12. #import <MediaPlayer/MediaPlayer.h>
  13. //hxd add 20240716
  14. #import "audioPlayListManager.h"
  15. #import "audioPlayingView.h"
  16. /**Asset KEY*/
  17. NSString * const DFPlayableKey = @"playable";
  18. /**PlayerItem KEY*/
  19. NSString * const DFStatusKey = @"status";
  20. NSString * const DFLoadedTimeRangesKey = @"loadedTimeRanges";
  21. NSString * const DFPlaybackBufferEmptyKey = @"playbackBufferEmpty";
  22. NSString * const DFPlaybackLikelyToKeepUpKey = @"playbackLikelyToKeepUp";
  23. @interface DFPlayer()<DFPlayerResourceLoaderDelegate>
  24. {
  25. BOOL _isOtherPlaying; // 其他应用是否正在播放
  26. BOOL _isBackground; // 是否进入后台
  27. BOOL _isCached; // 当前音频是否缓存
  28. BOOL _isSeek; // 正在seek
  29. BOOL _isSeekWaiting; // seek 等待
  30. BOOL _isNaturalToEndTime; // 是否是自然结束
  31. dispatch_group_t _netGroupQueue; // 组队列-网络
  32. dispatch_group_t _dataGroupQueue; // 组队列-数据
  33. NSInteger _currentAudioId; // 当前正在播放的音频Id
  34. NSInteger _randomIndex; // 随机数组元素index
  35. NSInteger _playIndex1; // 播放顺序标识
  36. NSInteger _playIndex2; // 播放顺序标识
  37. CGFloat _seekValue; // seek value
  38. NSMutableDictionary *_remoteInfoDictionary; // 控制中心信息
  39. }
  40. /** player */
  41. @property (nonatomic, strong) AVPlayer *player;
  42. /** playerItem */
  43. @property (nonatomic, strong) AVPlayerItem *playerItem;
  44. /** 播放进度监测 */
  45. @property (nonatomic, strong) id timeObserver;
  46. /** 随机数组 */
  47. @property (nonatomic, strong) NSMutableArray *randomIndexArray;
  48. /** 资源下载器 */
  49. @property (nonatomic, strong) DFPlayerResourceLoader *resourceLoader;
  50. @property (nonatomic, copy) void(^seekCompletionBlock)(void);
  51. @property (nonatomic, readwrite, strong) DFPlayerModel *currentAudioModel;
  52. @property (nonatomic, readwrite, strong) DFPlayerInfoModel *currentAudioInfoModel;
  53. @property (nonatomic, readwrite, assign) DFPlayerState state;
  54. @property (nonatomic, readwrite, assign) CGFloat bufferProgress;
  55. @property (nonatomic, readwrite, assign) CGFloat progress;
  56. @property (nonatomic, readwrite, assign) CGFloat currentTime;
  57. @property (nonatomic, readwrite, assign) CGFloat totalTime;
  58. @end
  59. @implementation DFPlayer
  60. #pragma mark - 初始化
  61. + (DFPlayer *)sharedPlayer {
  62. static DFPlayer *player = nil;
  63. static dispatch_once_t predicate;
  64. dispatch_once(&predicate, ^{
  65. player = [[[self class] alloc] init];
  66. });
  67. return player;
  68. }
  69. - (void)dealloc{
  70. [[NSNotificationCenter defaultCenter] removeObserver:self];
  71. }
  72. #pragma mark - 初始化播放器
  73. - (void)df_initPlayerWithUserId:(NSString *)userId{
  74. [DFPlayerFileManager df_saveUserId:userId];
  75. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  76. //hxd change 20240723
  77. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryMultiRoute error:nil];
  78. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  79. [[AVAudioSession sharedInstance] setActive:YES error:nil];
  80. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers error:nil];
  81. //[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback mode:(nonnull AVAudioSessionMode) options:<#(AVAudioSessionCategoryOptions)#> error:<#(NSError *__autoreleasing _Nullable * _Nullable)#>
  82. _isOtherPlaying = [AVAudioSession sharedInstance].otherAudioPlaying;
  83. self.playMode = DFPlayerModeOnlyOnce;
  84. self.state = DFPlayerStateStopped;
  85. self.isObserveProgress = YES;
  86. self.isObserveBufferProgress = YES;
  87. self.isNeedCache = YES;
  88. self.isObserveFileModifiedTime = NO;
  89. self.isObserveWWAN = NO;
  90. _isCached = NO;
  91. _isBackground = NO;
  92. _randomIndex = -1;
  93. _playIndex2 = 0;
  94. _netGroupQueue = dispatch_group_create();
  95. _dataGroupQueue = dispatch_group_create();
  96. [self addNetObserver];
  97. [self addPlayerObserver];
  98. [self addRemoteControlHandler];
  99. }
  100. - (void)addNetObserver{
  101. static dispatch_once_t token1;
  102. dispatch_once(&token1, ^{
  103. dispatch_group_enter(self->_netGroupQueue);
  104. });
  105. dispatch_group_async(_netGroupQueue, DFPlayerDefaultGlobalQueue, ^{
  106. [DFPlayerTool startMonitoringNetworkStatus:^(DFPlayerNetworkStatus networkStatus) {
  107. static dispatch_once_t token2;
  108. dispatch_once(&token2, ^{
  109. dispatch_group_leave(self->_netGroupQueue);
  110. });
  111. }];
  112. });
  113. }
  114. - (void)addPlayerObserver{
  115. //将要进入后台
  116. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  117. [notificationCenter addObserver:self
  118. selector:@selector(df_playerWillResignActive)
  119. name:UIApplicationWillResignActiveNotification
  120. object:nil];
  121. //已经进入前台
  122. [notificationCenter addObserver:self
  123. selector:@selector(df_playerDidEnterForeground)
  124. name:UIApplicationDidBecomeActiveNotification
  125. object:nil];
  126. //监测耳机
  127. [notificationCenter addObserver:self
  128. selector:@selector(df_playerAudioRouteChange:)
  129. name:AVAudioSessionRouteChangeNotification
  130. object:nil];
  131. //监听播放器被打断(别的软件播放音乐,来电话)
  132. [notificationCenter addObserver:self
  133. selector:@selector(df_playerAudioBeInterrupted:)
  134. name:AVAudioSessionInterruptionNotification
  135. object:[AVAudioSession sharedInstance]];
  136. //监测其他app是否占据AudioSession
  137. // [notificationCenter addObserver:self
  138. // selector:@selector(df_playerSecondaryAudioHint:)
  139. // name:AVAudioSessionSilenceSecondaryAudioHintNotification
  140. // object:nil];
  141. [notificationCenter addObserver:self
  142. selector:@selector(handleAudioSessionSilenceSecondaryAudioHintNotification:)
  143. name:AVAudioSessionSilenceSecondaryAudioHintNotification
  144. object:nil];
  145. // 监听中断通知
  146. [[NSNotificationCenter defaultCenter] addObserver:self
  147. selector:@selector(handleAudioSessionInterruption:)
  148. name:AVAudioSessionInterruptionNotification
  149. object:[AVAudioSession sharedInstance]];
  150. }
  151. - (void)df_playerWillResignActive{
  152. _isBackground = YES;
  153. }
  154. - (void)df_playerDidEnterForeground{
  155. _isBackground = NO;
  156. }
  157. - (void)df_playerAudioRouteChange:(NSNotification *)notification{
  158. NSInteger routeChangeReason = [notification.userInfo[AVAudioSessionRouteChangeReasonKey] integerValue];
  159. switch (routeChangeReason) {
  160. case AVAudioSessionRouteChangeReasonNewDeviceAvailable://耳机插入
  161. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:isHeadphone:)]) {
  162. [self.delegate df_player:self isHeadphone:YES];
  163. }
  164. break;
  165. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable://耳机拔出,停止播放操作
  166. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:isHeadphone:)]) {
  167. [self.delegate df_player:self isHeadphone:NO];
  168. }else{
  169. [self df_pause];
  170. }
  171. break;
  172. case AVAudioSessionRouteChangeReasonCategoryChange:
  173. //
  174. break;
  175. default:
  176. break;
  177. }
  178. }
  179. - (void)df_playerAudioBeInterrupted:(NSNotification *)notification{
  180. NSDictionary *dic = notification.userInfo;
  181. if ([dic[AVAudioSessionInterruptionTypeKey] integerValue] == 1) {//打断开始
  182. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:isInterrupted:)]) {
  183. [self.delegate df_player:self isInterrupted:YES];
  184. }else{
  185. [self df_pause];
  186. }
  187. }else {//打断结束
  188. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:isInterrupted:)]) {
  189. [self.delegate df_player:self isInterrupted:NO];
  190. }else{
  191. if ([notification.userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == 1) {
  192. [self df_play];
  193. }
  194. }
  195. }
  196. }
  197. - (void)df_playerSecondaryAudioHint:(NSNotification *)notification{
  198. // NSInteger type = [notification.userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey] integerValue];
  199. }
  200. -(void)df_playerDidPlayToEndTime:(NSNotification *)notification{
  201. if (self.delegate && [self.delegate respondsToSelector:@selector(df_playerDidPlayToEndTime:)]) {
  202. [self.delegate df_playerDidPlayToEndTime:self];
  203. }else{
  204. _isNaturalToEndTime = YES;
  205. [self df_next];
  206. }
  207. }
  208. /**远程线控*/
  209. - (void)addRemoteControlHandler{
  210. if (@available (iOS 7.1, *)) {
  211. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  212. MPRemoteCommandCenter *center = [MPRemoteCommandCenter sharedCommandCenter];
  213. [self addRemoteCommand:center.playCommand selector:@selector(df_play)];
  214. [self addRemoteCommand:center.pauseCommand selector:@selector(df_pause)];
  215. [self addRemoteCommand:center.previousTrackCommand selector:@selector(df_last)];
  216. [self addRemoteCommand:center.nextTrackCommand selector:@selector(df_next)];
  217. [center.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
  218. if ([DFPlayer sharedPlayer].state == DFPlayerStatePlaying) {
  219. [[DFPlayer sharedPlayer] df_pause];
  220. }else{
  221. [[DFPlayer sharedPlayer] df_play];
  222. }
  223. return MPRemoteCommandHandlerStatusSuccess;
  224. }];
  225. if (@available (iOS 9.1,*)) {
  226. [center.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
  227. MPChangePlaybackPositionCommandEvent *positionEvent = (MPChangePlaybackPositionCommandEvent *)event;
  228. if (self.totalTime > 0) {
  229. [self df_seekToTime:positionEvent.positionTime / self.totalTime completionBlock:nil];
  230. }
  231. return MPRemoteCommandHandlerStatusSuccess;
  232. }];
  233. }
  234. }
  235. }
  236. - (void)addRemoteCommand:(MPRemoteCommand *)command selector:(SEL)selector{
  237. [command addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
  238. if ([self respondsToSelector:selector]) {
  239. IMP imp = [self methodForSelector:selector];
  240. void (*func)(id, SEL) = (void *)imp;
  241. func(self, selector);
  242. }
  243. return MPRemoteCommandHandlerStatusSuccess;
  244. }];
  245. }
  246. #pragma mark - 数据源
  247. - (void)df_reloadData{
  248. if (self.dataSource && [self.dataSource respondsToSelector:@selector(df_audioDataForPlayer:)]) {
  249. if (!self.playerModelArray) {
  250. self.playerModelArray = [NSMutableArray array];
  251. }
  252. if (self.playerModelArray.count != 0) {
  253. [self.playerModelArray removeAllObjects];
  254. }
  255. dispatch_group_enter(_dataGroupQueue);
  256. dispatch_group_async(_dataGroupQueue, DFPlayerHighGlobalQueue, ^{
  257. dispatch_async(DFPlayerHighGlobalQueue, ^{
  258. [self.playerModelArray addObjectsFromArray:[self.dataSource df_audioDataForPlayer:self]];
  259. //更新随机数组
  260. [self updateRandomIndexArray];
  261. //更新currentAudioId
  262. if (self.currentAudioModel.audioUrl) {
  263. [self.playerModelArray enumerateObjectsWithOptions:(NSEnumerationConcurrent) usingBlock:^(DFPlayerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  264. if ([obj.audioUrl.absoluteString isEqualToString:self.currentAudioModel.audioUrl.absoluteString]) {
  265. self.currentAudioModel.audioId = idx;
  266. self->_currentAudioId = idx;
  267. *stop = YES;
  268. }
  269. }];
  270. }
  271. dispatch_group_leave(self->_dataGroupQueue);
  272. });
  273. });
  274. }
  275. }
  276. #pragma mark - 播放 IMPORTANT
  277. - (void)df_playWithAudioId:(NSUInteger)audioId{
  278. dispatch_group_notify(_dataGroupQueue, DFPlayerHighGlobalQueue, ^{
  279. if (self.playerModelArray.count > audioId) {
  280. self.currentAudioModel = self.playerModelArray[audioId];
  281. self->_currentAudioId = audioId;
  282. [self audioPrePlay];
  283. }
  284. });
  285. }
  286. - (void)audioPrePlay{
  287. [self reset];
  288. if (![DFPlayerTool isNSURL:self.currentAudioModel.audioUrl]) {
  289. return;
  290. }
  291. //hxd add 20240716 去下载 自己管理缓存
  292. if(!self.currentAudioModel.didCacheWorkType){
  293. [[audioPlayListManager shareManager] beginToDownloadByUrl:self.currentAudioModel.audioUrl.absoluteString];
  294. self.currentAudioModel.didCacheWorkType = YES;
  295. }
  296. //[[audioPlayListManager shareManager] beginToDownloadByUrl:self.currentAudioModel.audioUrl.absoluteString];
  297. if (self.dataSource && [self.dataSource respondsToSelector:@selector(df_audioInfoForPlayer:)]) {
  298. self.currentAudioInfoModel = [self.dataSource df_audioInfoForPlayer:self];
  299. }
  300. if (self.delegate && [self.delegate respondsToSelector:@selector(df_playerAudioAddToPlayQueue:)]) {
  301. [self.delegate df_playerAudioAddToPlayQueue:self];
  302. }
  303. //hxd add 20240716 判断下载完成了没有 完成了 就修改 audioUrl
  304. if ([DFPlayerTool isLocalAudio:self.currentAudioModel.audioUrl]){
  305. NSString*filePath = [[audioPlayListManager shareManager] checkFileToDownloadDonewith:self.currentAudioModel.audioUrl.absoluteString];
  306. if(filePath.length > 0)
  307. {
  308. NSURL *loaclUrl = [NSURL fileURLWithPath:filePath];
  309. if(loaclUrl){
  310. self.currentAudioModel.audioUrl = loaclUrl;
  311. }
  312. }
  313. }
  314. [[audioPlayingView sharedInstance] setAudioTitleFunBy:self.currentAudioModel.audioId];
  315. [[audioPlayingView sharedInstance] setAudioPlayingStateFunBy:YES];
  316. if ([DFPlayerTool isLocalAudio:self.currentAudioModel.audioUrl]) {
  317. // NSLog(@"-- DFPlayer:本地音频,Id:%ld",(unsigned long)self.currentAudioModel.audioId);
  318. _isCached = YES;
  319. [self loadPlayerItemWithURL:self.currentAudioModel.audioUrl];
  320. }else{
  321. NSString *cachePath = [DFPlayerFileManager df_cachePath:self.currentAudioModel.audioUrl];
  322. _isCached = cachePath ? YES : NO;
  323. // NSLog(@"-- DFPlayer:网络音频,Id:%ld 缓存:%@",(unsigned long)self.currentAudioModel.audioId, cachePath ? @"有" : @"无");
  324. dispatch_group_notify(_netGroupQueue, DFPlayerDefaultGlobalQueue, ^{
  325. if ([DFPlayerTool networkStatus] == DFPlayerNetworkStatusUnknown ||
  326. [DFPlayerTool networkStatus] == DFPlayerNetworkStatusNotReachable){
  327. if (cachePath){//有缓存,播放缓存
  328. [self loadPlayerItemWithURL:[NSURL fileURLWithPath:cachePath]];
  329. }else{//无缓存,提示联网
  330. [self df_getStatusCode:DFPlayerStatusNoNetwork];
  331. }
  332. }else{
  333. if (!self.isNeedCache){//不需要缓存
  334. // WWAN网络警告
  335. if (self.isObserveWWAN && [DFPlayerTool networkStatus] == DFPlayerNetworkStatusReachableViaWWAN) {
  336. [self df_getStatusCode:DFPlayerStatusViaWWAN];
  337. return;
  338. }
  339. [self loadPlayerItemWithURL:self.currentAudioModel.audioUrl];
  340. }else{//需要缓存
  341. if (cachePath && !self.isObserveFileModifiedTime) {
  342. //有缓存且不监听改变时间,直接播放缓存
  343. [self loadPlayerItemWithURL:[NSURL fileURLWithPath:cachePath]];
  344. }else{//无缓存 或 需要兼听
  345. // WWAN网络警告
  346. if (self.isObserveWWAN && [DFPlayerTool networkStatus] == DFPlayerNetworkStatusReachableViaWWAN) {
  347. [self df_getStatusCode:DFPlayerStatusViaWWAN];
  348. return;
  349. }
  350. [self loadAudioWithCachePath:cachePath];
  351. }
  352. }
  353. }
  354. });
  355. }
  356. }
  357. - (void)loadAudioWithCachePath:(NSString *)cachePath{
  358. self.resourceLoader = [[DFPlayerResourceLoader alloc] init];
  359. self.resourceLoader.delegate = self;
  360. self.resourceLoader.isCached = _isCached;
  361. self.resourceLoader.isObserveFileModifiedTime = self.isObserveFileModifiedTime;
  362. NSURL *customUrl = [DFPlayerTool customURL:self.currentAudioModel.audioUrl];
  363. if (!customUrl) {
  364. return;
  365. }
  366. AVURLAsset *asset = [AVURLAsset URLAssetWithURL:customUrl options:nil];
  367. [asset.resourceLoader setDelegate:self.resourceLoader queue:dispatch_get_main_queue()];
  368. [asset loadValuesAsynchronouslyForKeys:@[DFPlayableKey] completionHandler:^{
  369. dispatch_async( dispatch_get_main_queue(),^{
  370. if (!asset.playable) {
  371. self.state = DFPlayerStateFailed;
  372. [self.resourceLoader stopDownload];
  373. [asset cancelLoading];
  374. }
  375. });
  376. }];
  377. DFPlayerWeakSelf
  378. self.resourceLoader.checkStatusBlock = ^(NSInteger statusCode){
  379. DFPlayerStrongSelf
  380. if (statusCode == 200) {
  381. [sSelf loadPlayerItemWithAsset:asset];
  382. }else if (statusCode == 304) { // 服务器文件未变化
  383. [sSelf loadPlayerItemWithURL:[NSURL fileURLWithPath:cachePath]];
  384. }else if (statusCode == 206){
  385. }
  386. };
  387. }
  388. - (void)loadPlayerItemWithURL:(NSURL *)URL{
  389. self.playerItem = [[AVPlayerItem alloc] initWithURL:URL];
  390. [self loadPlayer];
  391. }
  392. - (void)loadPlayerItemWithAsset:(AVURLAsset *)asset{
  393. self.playerItem = [AVPlayerItem playerItemWithAsset:asset];
  394. [self loadPlayer];
  395. }
  396. - (void)loadPlayer{
  397. self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
  398. if (@available(iOS 10.0,*)) {
  399. self.player.automaticallyWaitsToMinimizeStalling = NO;
  400. }
  401. [self df_play];
  402. [self addProgressObserver];
  403. [self addPlayingCenterInfo];
  404. }
  405. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
  406. if (object == self.player.currentItem) {
  407. if ([keyPath isEqualToString:DFStatusKey]) {
  408. AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
  409. switch (status) {
  410. case AVPlayerItemStatusUnknown:
  411. self.state = DFPlayerStateFailed;
  412. [self df_getStatusCode:DFPlayerStatusUnknown];
  413. break;
  414. case AVPlayerItemStatusReadyToPlay:
  415. if (self.delegate && [self.delegate respondsToSelector:@selector(df_playerReadyToPlay:)]) {
  416. [self.delegate df_playerReadyToPlay:self];
  417. }
  418. break;
  419. case AVPlayerItemStatusFailed:
  420. //NSError *error = nil;//self.player.currentItem.error;
  421. NSLog(@"111:%@",self.player.currentItem.error);
  422. self.state = DFPlayerStateFailed;
  423. [self df_getStatusCode:DFPlayerStatusFailed];
  424. break;
  425. default:
  426. break;
  427. }
  428. }else if ([keyPath isEqualToString:DFLoadedTimeRangesKey]) {
  429. [self addBufferProgressObserver];
  430. }else if ([keyPath isEqualToString:DFPlaybackBufferEmptyKey]) {
  431. if (self.playerItem.playbackBufferEmpty) {
  432. self.state = DFPlayerStateBuffering;
  433. }
  434. }else if ([keyPath isEqualToString:DFPlaybackLikelyToKeepUpKey]) {
  435. }
  436. }else{
  437. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  438. }
  439. }
  440. #pragma mark - DFPlayerResourceLoaderDelegate
  441. /**下载出错*/
  442. - (void)loader:(DFPlayerResourceLoader *)loader requestError:(NSInteger)errorCode{
  443. if (errorCode == NSURLErrorTimedOut) {
  444. [self df_getStatusCode:DFPlayerStatusTimeOut];
  445. }else if ([DFPlayerTool networkStatus] == DFPlayerNetworkStatusNotReachable ||
  446. [DFPlayerTool networkStatus] == DFPlayerNetworkStatusUnknown) {
  447. [self df_getStatusCode:DFPlayerStatusNoNetwork];
  448. }
  449. }
  450. /**是否完成缓存*/
  451. - (void)loader:(DFPlayerResourceLoader *)loader isCached:(BOOL)isCached{
  452. _isCached = isCached;
  453. NSUInteger status = isCached ? DFPlayerStatusCacheSucc : DFPlayerStatusCacheFail;
  454. [self df_getStatusCode:status];
  455. }
  456. #pragma mark - 缓冲进度 播放进度 歌曲锁屏信息 音频跳转
  457. - (void)addBufferProgressObserver{
  458. self.totalTime = CMTimeGetSeconds(self.playerItem.duration);
  459. if (!self.isObserveBufferProgress) {
  460. return;
  461. }
  462. CMTimeRange timeRange = [self.playerItem.loadedTimeRanges.firstObject CMTimeRangeValue];
  463. CGFloat startSeconds = CMTimeGetSeconds(timeRange.start);
  464. CGFloat durationSeconds = CMTimeGetSeconds(timeRange.duration);
  465. if (self.totalTime != 0) {//避免出现inf
  466. self.bufferProgress = (startSeconds + durationSeconds) / self.totalTime;
  467. }
  468. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:bufferProgress:)]) {
  469. [self.delegate df_player:self bufferProgress:self.bufferProgress];
  470. }
  471. if (_isSeekWaiting) {
  472. if (self.bufferProgress > _seekValue) {
  473. _isSeekWaiting = NO;
  474. [self didSeekToTime:_seekValue completionBlock:^{
  475. if (self.seekCompletionBlock) {
  476. self.seekCompletionBlock();
  477. }
  478. }];
  479. }
  480. }
  481. }
  482. - (void)addProgressObserver{
  483. if (!self.isObserveProgress) {
  484. return;
  485. }
  486. DFPlayerWeakSelf
  487. self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, 1.0) queue:nil usingBlock:^(CMTime time){
  488. DFPlayerStrongSelf
  489. if (sSelf->_isSeek) {
  490. return;
  491. }
  492. AVPlayerItem *currentItem = sSelf.playerItem;
  493. NSArray *loadedRanges = currentItem.seekableTimeRanges;
  494. if (loadedRanges.count > 0 && currentItem.duration.timescale != 0){
  495. CGFloat currentT = (CGFloat)CMTimeGetSeconds(time);
  496. sSelf.currentTime = currentT;
  497. if (sSelf.totalTime != 0) {//避免出现inf
  498. sSelf.progress = CMTimeGetSeconds([currentItem currentTime]) / sSelf.totalTime;
  499. }
  500. if (sSelf.delegate && [sSelf.delegate respondsToSelector:@selector(df_player:progress:currentTime:)]) {
  501. [sSelf.delegate df_player:sSelf progress:sSelf.progress currentTime:currentT];
  502. }
  503. [sSelf updatePlayingCenterInfo];
  504. }
  505. }];
  506. }
  507. - (void)addPlayingCenterInfo{
  508. _remoteInfoDictionary = [NSMutableDictionary dictionary];
  509. if (self.currentAudioInfoModel.audioName) {
  510. _remoteInfoDictionary[MPMediaItemPropertyTitle] = self.currentAudioInfoModel.audioName;
  511. }
  512. if (self.currentAudioInfoModel.audioAlbum) {
  513. _remoteInfoDictionary[MPMediaItemPropertyAlbumTitle] = self.currentAudioInfoModel.audioAlbum;
  514. }
  515. if (self.currentAudioInfoModel.audioSinger) {
  516. _remoteInfoDictionary[MPMediaItemPropertyArtist] = self.currentAudioInfoModel.audioSinger;
  517. }
  518. if ([self.currentAudioInfoModel.audioImage isKindOfClass:[UIImage class]] && self.currentAudioInfoModel.audioImage) {
  519. if (@available(iOS 10.0, *)) {
  520. DFPlayerWeakSelf
  521. MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:self.currentAudioInfoModel.audioImage.size
  522. requestHandler:^UIImage * _Nonnull(CGSize size) {
  523. return wSelf.currentAudioInfoModel.audioImage;
  524. }];
  525. _remoteInfoDictionary[MPMediaItemPropertyArtwork] = artwork;
  526. } else {
  527. MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:self.currentAudioInfoModel.audioImage];
  528. _remoteInfoDictionary[MPMediaItemPropertyArtwork] = artwork;
  529. }
  530. }
  531. _remoteInfoDictionary[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithFloat:1.0];
  532. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = _remoteInfoDictionary;
  533. }
  534. - (void)updatePlayingCenterInfo{
  535. if (!_isBackground) {return;}
  536. _remoteInfoDictionary[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithDouble:CMTimeGetSeconds(self.playerItem.currentTime)];
  537. _remoteInfoDictionary[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithDouble:CMTimeGetSeconds(self.playerItem.duration)];
  538. [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = _remoteInfoDictionary;
  539. }
  540. - (void)df_seekToTime:(CGFloat)value completionBlock:(void (^)(void))completionBlock{
  541. _isSeek = YES;
  542. // 先暂停
  543. if (self.state == DFPlayerStatePlaying) {
  544. [self df_pause];
  545. }
  546. if (self.bufferProgress < value) {
  547. _isSeekWaiting = YES;
  548. _seekValue = value;
  549. if (completionBlock) {
  550. self.seekCompletionBlock = completionBlock;
  551. }
  552. }else{
  553. _isSeekWaiting = NO;
  554. [self didSeekToTime:value completionBlock:completionBlock];
  555. }
  556. }
  557. - (void)didSeekToTime:(CGFloat)value completionBlock:(void (^)(void))completionBlock{
  558. [self.player seekToTime:CMTimeMake(floorf(self.totalTime * value), 1)
  559. toleranceBefore:kCMTimeZero
  560. toleranceAfter:kCMTimeZero
  561. completionHandler:^(BOOL finished) {
  562. if (finished) {
  563. [self df_play];
  564. self->_isSeek = NO;
  565. if (completionBlock) {
  566. completionBlock();
  567. }
  568. }
  569. }];
  570. }
  571. /**倍速播放*/
  572. - (void)df_setRate:(CGFloat)rate{
  573. for (AVPlayerItemTrack *track in self.playerItem.tracks){
  574. if ([track.assetTrack.mediaType isEqual:AVMediaTypeAudio]){
  575. track.enabled = YES;
  576. }
  577. }
  578. self.player.rate = rate;
  579. }
  580. /**释放播放器*/
  581. - (void)df_deallocPlayer{
  582. [self reset];
  583. self.state = DFPlayerStateStopped;
  584. [DFPlayerTool stopMonitoringNetwork];
  585. if (@available(iOS 7.1, *)) {
  586. [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  587. MPRemoteCommandCenter *center = [MPRemoteCommandCenter sharedCommandCenter];
  588. [[center playCommand] removeTarget:self];
  589. [[center pauseCommand] removeTarget:self];
  590. [[center nextTrackCommand] removeTarget:self];
  591. [[center previousTrackCommand] removeTarget:self];
  592. [[center togglePlayPauseCommand] removeTarget:self];
  593. if(@available(iOS 9.1, *)) {
  594. [center.changePlaybackPositionCommand removeTarget:self];
  595. }
  596. }
  597. if (_isOtherPlaying) {
  598. [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
  599. }else{
  600. [[AVAudioSession sharedInstance] setActive:NO error:nil];
  601. }
  602. [self.player.currentItem cancelPendingSeeks];
  603. [self.player.currentItem.asset cancelLoading];
  604. if (self.randomIndexArray) {
  605. self.randomIndexArray = nil;
  606. }
  607. if (self.playerModelArray) {
  608. self.playerModelArray = nil;
  609. }
  610. if (self.playerItem) {
  611. self.playerItem = nil;
  612. }
  613. if (self.player) {
  614. self.player = nil;
  615. }
  616. [[DFPlayerUIManager sharedManager] dfUI_deallocPlayer];
  617. }
  618. - (void)reset{
  619. if (self.state == DFPlayerStatePlaying) {
  620. [self df_pause];
  621. }
  622. //停止下载
  623. if (self.resourceLoader) {
  624. [self.resourceLoader stopDownload];
  625. }
  626. //移除进度观察者
  627. if (self.timeObserver) {
  628. [self.player removeTimeObserver:self.timeObserver];
  629. self.timeObserver = nil;
  630. }
  631. //重置
  632. self.progress = .0f;
  633. self.bufferProgress = .0f;
  634. self.currentTime = .0f;
  635. self.totalTime = .0f;
  636. _isSeekWaiting = NO;
  637. }
  638. #pragma mark - 播放 暂停 下一首 上一首
  639. /**播放*/
  640. -(void)df_play{
  641. self.state = DFPlayerStatePlaying;
  642. [self.player play];
  643. }
  644. /**暂停*/
  645. -(void)df_pause{
  646. self.state = DFPlayerStatePause;
  647. [self.player pause];
  648. //hxd add 20240721
  649. [[audioPlayingView sharedInstance] setAudioPlayingStateFunBy:NO];
  650. }
  651. /**下一首*/
  652. - (void)df_next{
  653. switch (self.playMode) {
  654. case DFPlayerModeOnlyOnce:
  655. if (_isNaturalToEndTime) {
  656. _isNaturalToEndTime = NO;
  657. [self df_pause];
  658. }else{
  659. [self next];
  660. }
  661. break;
  662. case DFPlayerModeSingleCycle:
  663. if (_isNaturalToEndTime) {
  664. _isNaturalToEndTime = NO;
  665. [self audioPrePlay];
  666. }else{
  667. [self next];
  668. }
  669. break;
  670. case DFPlayerModeOrderCycle:
  671. [self next];
  672. break;
  673. case DFPlayerModeShuffleCycle:{
  674. _playIndex2++;
  675. _currentAudioId = [self randomAudioId];
  676. self.currentAudioModel = self.playerModelArray[_currentAudioId];
  677. [self audioPrePlay];
  678. break;
  679. }
  680. default:
  681. break;
  682. }
  683. }
  684. /**上一首*/
  685. - (void)df_last{
  686. if (self.playMode == DFPlayerModeShuffleCycle) {
  687. if (_playIndex2 == 1) {
  688. _playIndex2 = 0;
  689. self.currentAudioModel = self.playerModelArray[_playIndex1];
  690. }else{
  691. _currentAudioId = [self randomAudioId];
  692. self.currentAudioModel = self.playerModelArray[_currentAudioId];
  693. }
  694. [self audioPrePlay];
  695. }else{
  696. _currentAudioId--;
  697. if (_currentAudioId < 0) {
  698. _currentAudioId = self.playerModelArray.count - 1;
  699. }
  700. self.currentAudioModel = self.playerModelArray[_currentAudioId];
  701. [self audioPrePlay];
  702. }
  703. }
  704. - (void)next{
  705. _currentAudioId++;
  706. if (_currentAudioId < 0 || _currentAudioId >= self.playerModelArray.count) {
  707. _currentAudioId = 0;
  708. }
  709. _playIndex1 = _currentAudioId;
  710. _playIndex2 = 0;
  711. self.currentAudioModel = self.playerModelArray[_currentAudioId];
  712. [self audioPrePlay];
  713. }
  714. #pragma mark - 随机播放相关
  715. - (void)updateRandomIndexArray{
  716. NSInteger startIndex = 0;
  717. NSInteger length = self.playerModelArray.count;
  718. NSInteger endIndex = startIndex+length;
  719. NSMutableArray *arr = [NSMutableArray arrayWithCapacity:length];
  720. NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:length];
  721. for (NSInteger i = startIndex; i < endIndex; i++) {
  722. @autoreleasepool {
  723. NSString *str = [NSString stringWithFormat:@"%ld",(long)i];
  724. [arr1 addObject:str];
  725. }
  726. }
  727. for (NSInteger i = startIndex; i < endIndex; i++) {
  728. @autoreleasepool {
  729. int index = arc4random()%arr1.count;
  730. int radom = [arr1[index] intValue];
  731. NSNumber *num = [NSNumber numberWithInt:radom];
  732. [arr addObject:num];
  733. [arr1 removeObjectAtIndex:index];
  734. }
  735. }
  736. _randomIndexArray = [NSMutableArray arrayWithArray:arr];
  737. }
  738. - (NSInteger)randomAudioId{
  739. _randomIndex++;
  740. if (_randomIndex >= self.randomIndexArray.count) {
  741. _randomIndex = 0;
  742. }
  743. if (_randomIndex < 0) {
  744. _randomIndex = self.randomIndexArray.count - 1;
  745. }
  746. NSInteger index = [self.randomIndexArray[_randomIndex] integerValue];
  747. //去重
  748. //hxd change 20240721 仅有一首歌时 一直为0 不能去重
  749. if (index == _currentAudioId && index != 0) {
  750. index = [self randomAudioId];
  751. }
  752. return index;
  753. }
  754. #pragma mark - setter
  755. - (void)setCategory:(AVAudioSessionCategory)category{
  756. [[AVAudioSession sharedInstance] setCategory:category error:nil];
  757. }
  758. - (void)setPlayerItem:(AVPlayerItem *)playerItem{
  759. if (_playerItem == playerItem) {
  760. return;
  761. }
  762. if (_playerItem) {
  763. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
  764. [_playerItem removeObserver:self forKeyPath:DFStatusKey];
  765. [_playerItem removeObserver:self forKeyPath:DFLoadedTimeRangesKey];
  766. [_playerItem removeObserver:self forKeyPath:DFPlaybackBufferEmptyKey];
  767. [_playerItem removeObserver:self forKeyPath:DFPlaybackLikelyToKeepUpKey];
  768. }
  769. _playerItem = playerItem;
  770. if (playerItem) {
  771. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(df_playerDidPlayToEndTime:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
  772. [playerItem addObserver:self forKeyPath:DFStatusKey options:NSKeyValueObservingOptionNew context:nil];
  773. [playerItem addObserver:self forKeyPath:DFLoadedTimeRangesKey options:NSKeyValueObservingOptionNew context:nil];
  774. [playerItem addObserver:self forKeyPath:DFPlaybackBufferEmptyKey options:NSKeyValueObservingOptionNew context:nil];
  775. [playerItem addObserver:self forKeyPath:DFPlaybackLikelyToKeepUpKey options:NSKeyValueObservingOptionNew context:nil];
  776. }
  777. }
  778. #pragma mark - 缓存相关
  779. - (NSString *)df_cachePath:(NSURL *)audioUrl{
  780. if ([DFPlayerTool isLocalAudio:audioUrl] || ![DFPlayerTool isNSURL:audioUrl] || !audioUrl) {
  781. return nil;
  782. }
  783. return [DFPlayerFileManager df_cachePath:audioUrl];
  784. }
  785. - (CGFloat)df_cacheSize:(BOOL)currentUser{
  786. return [DFPlayerFileManager df_cacheSize:currentUser];
  787. }
  788. - (BOOL)df_clearAudioCache:(NSURL *)audioUrl{
  789. return [DFPlayerFileManager df_clearAudioCache:audioUrl];
  790. }
  791. - (BOOL)df_clearUserCache:(BOOL)currentUser{
  792. return [DFPlayerFileManager df_clearUserCache:currentUser];
  793. }
  794. #pragma mark - 统一状态代理
  795. - (void)df_getStatusCode:(NSUInteger)statusCode{
  796. dispatch_async(dispatch_get_main_queue(), ^{
  797. if (self.delegate && [self.delegate respondsToSelector:@selector(df_player:didGetStatusCode:)]) {
  798. [self.delegate df_player:self didGetStatusCode:statusCode];
  799. }
  800. });
  801. }
  802. #pragma mark - hxd add 20240725 音频播放呗中断检测
  803. - (void)handleAudioSessionInterruption:(NSNotification *)notification {
  804. if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
  805. AVAudioSessionInterruptionType type = [[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  806. switch (type) {
  807. case AVAudioSessionInterruptionTypeBegan:
  808. // 播放被中断,此处可以暂停播放
  809. HLog(@"Audio Session Interruption Began");
  810. // 暂停你的音频播放
  811. [self df_pause];
  812. break;
  813. case AVAudioSessionInterruptionTypeEnded:
  814. // 播放中断结束,检查是否应该恢复播放
  815. HLog(@"Audio Session Interruption Ended");
  816. // 获取中断选项,判断是否可以恢复播放
  817. AVAudioSessionInterruptionOptions options = [[notification.userInfo valueForKey:AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
  818. if (options == AVAudioSessionInterruptionOptionShouldResume) {
  819. // 如果应该恢复播放,则恢复播放
  820. [self df_play];
  821. }
  822. break;
  823. default:
  824. break;
  825. }
  826. }
  827. }
  828. - (void)handleAudioSessionSilenceSecondaryAudioHintNotification:(NSNotification *)notification {
  829. // 这里处理通知,比如暂停或恢复你的音频播放
  830. //AVAudioSession *session = [notification object];
  831. BOOL willSilenceOthers = [[notification.userInfo valueForKey:AVAudioSessionSilenceSecondaryAudioHintTypeKey] boolValue];
  832. if (willSilenceOthers) {
  833. // 其他音频将被暂停
  834. HLog(@"Other audio will be silenced.");
  835. // 这里可以添加代码来暂停你的音频播放(如果需要的话)
  836. [self df_pause];
  837. } else {
  838. // 其他音频将恢复播放
  839. HLog(@"Other audio will resume.");
  840. // 这里可以添加代码来恢复你的音频播放(如果需要的话)
  841. [self df_play];
  842. }
  843. }
  844. @end