AudioSessionObject.m 5.5 KB

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