AudioSessionObject.m 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. //
  2. // AudioSessionObject.m
  3. // 隐私保护
  4. //
  5. // Created by xd h on 2023/10/24.
  6. //
  7. #import "AudioSessionObject.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <AudioToolbox/AudioToolbox.h>
  10. #import "DFPlayer.h"//这个播放音乐的第三方 这个播放静音会影响到音乐后台播放
  11. @interface AudioSessionObject()
  12. @property (strong, nonatomic) AVAudioPlayer *audioPlayer;
  13. @property (strong,nonatomic) NSTimer *timer;
  14. @property (nonatomic, assign) UIBackgroundTaskIdentifier backgrounTask;
  15. @end
  16. @implementation AudioSessionObject
  17. /// 创建单利
  18. + (AudioSessionObject *)shareManager{
  19. static AudioSessionObject *manager = nil;
  20. static dispatch_once_t onceToken;
  21. dispatch_once(&onceToken, ^{
  22. manager = [[AudioSessionObject alloc]init];
  23. });
  24. return manager;
  25. }
  26. - (instancetype)init {
  27. self = [super init];
  28. if (self) {
  29. [self addNoti];
  30. [self creatAVAudioSessionObject];
  31. }
  32. return self;
  33. }
  34. - (void)addNoti {
  35. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
  36. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  37. }
  38. - (void)appWillEnterForeground {
  39. NSLog(@"%@ appWillEnterForeground",NSStringFromClass([self class]));
  40. [self stopPlayAudioSession];
  41. [self.timer invalidate];
  42. _isBackgroundType = NO;
  43. // 恢复音频播放 AVAudioSessionCategoryPlayback 可以在开启静音后播放声音 但是 停止后台播放后 [[AVAudioSession sharedInstance] setActive: No error: nil] 后无声音了 AVAudioSessionCategorySoloAmbient 可以 但是开启静音后无声
  44. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
  45. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];//ok
  46. //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil]; // ok
  47. //[[AVAudioSession sharedInstance] setActive: YES error: nil];
  48. [[AVAudioSession sharedInstance] setActive:YES error: nil];
  49. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  50. }
  51. - (void)appDidEnterBackground {
  52. NSLog(@"%@ appDidEnterBackground",NSStringFromClass([self class]));
  53. if([DFPlayer sharedPlayer].state == DFPlayerStateBuffering
  54. ||[DFPlayer sharedPlayer].state == DFPlayerStatePlaying){
  55. return;
  56. }
  57. _isBackgroundType = YES;
  58. BOOL isBackground = [HWDataManager getBoolWithKey:stringKeyAddSn(Const_file_Transfe_working_background)];
  59. if (!isBackground) {
  60. [self stopBackgroundActiveFun];
  61. return;
  62. }
  63. [[AVAudioSession sharedInstance] setActive: YES error: nil];
  64. [self startPlayAudioSession];
  65. //申请后台
  66. self.backgrounTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  67. [[UIApplication sharedApplication] endBackgroundTask:self.backgrounTask];
  68. self.backgrounTask = UIBackgroundTaskInvalid;
  69. }];
  70. self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(applyToSystemForMoreTime) userInfo:nil repeats:YES];
  71. [self.timer setFireDate:[NSDate distantPast]];
  72. }
  73. /// 创建音乐播放器
  74. - (void)creatAVAudioSessionObject{
  75. //设置后台模式和锁屏模式下依然能够播放
  76. [[AVAudioSession sharedInstance] setActive: YES error: nil];
  77. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
  78. //初始化音频播放器
  79. NSError *playerError;
  80. NSString*pathStr = [[NSBundle mainBundle] pathForResource:@"RunInBackground" ofType:@"mp3"];
  81. NSURL *urlSound11 = [[NSURL alloc] initFileURLWithPath:pathStr];
  82. // HLog(@"%@---%@",pathStr,urlSound11);
  83. //NSURL *urlSound = [[NSURL alloc]initWithString:pathStr];
  84. _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlSound11 error:&playerError];
  85. _audioPlayer.numberOfLoops = -1;//无限播放
  86. //_audioPlayer.volume = 0;
  87. }
  88. /// 开始播放声音
  89. - (void)startPlayAudioSession{
  90. NSLog(@"%@ startPlayAudioSession",NSStringFromClass([self class]));
  91. [_audioPlayer play];
  92. _isBackgroundType = YES;
  93. }
  94. /// 停止播放声音
  95. - (void)stopPlayAudioSession{
  96. NSLog(@"%@ stopPlayAudioSession",NSStringFromClass([self class]));
  97. [_audioPlayer stop];
  98. _isBackgroundType = NO;
  99. }
  100. - (void)stopBackgroundActiveFun
  101. {
  102. if(!_isBackgroundType){
  103. return;
  104. }
  105. [self stopPlayAudioSession];
  106. [self.timer invalidate];
  107. [[AVAudioSession sharedInstance] setActive:NO withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error: nil];
  108. //[[AVAudioSession sharedInstance] setActive:NO error: nil];
  109. [[UIApplication sharedApplication] endBackgroundTask:self.backgrounTask];
  110. self.backgrounTask = UIBackgroundTaskInvalid;
  111. }
  112. #pragma mark - 定时器设置判断后台保活时间,如果将要被后台杀死,重新唤醒
  113. - (void)applyToSystemForMoreTime {
  114. //HLog(@"我还在后台运行 哈哈");
  115. // if ([UIApplication sharedApplication].backgroundTimeRemaining < 20.0) {//如果剩余时间小于30秒
  116. // [[UIApplication sharedApplication] endBackgroundTask:self.backgrounTask];
  117. // self.backgrounTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  118. // [[UIApplication sharedApplication] endBackgroundTask:self.backgrounTask];
  119. // self.backgrounTask = UIBackgroundTaskInvalid;
  120. // }];
  121. // }
  122. }
  123. @end