//
//  AudioSessionObject.m
//  隐私保护
//
//  Created by xd h on 2023/10/24.
//

#import "AudioSessionObject.h"

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface AudioSessionObject()
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong,nonatomic) NSTimer *timer;
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgrounTask;


@end

@implementation AudioSessionObject

/// 创建单利
+ (AudioSessionObject *)shareManager{
   static AudioSessionObject *manager = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       manager = [[AudioSessionObject alloc]init];
   });
   return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self addNoti];
        [self creatAVAudioSessionObject];
    }
    return self;
}

- (void)addNoti {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
}

- (void)appWillEnterForeground {
    NSLog(@"%@ appWillEnterForeground",NSStringFromClass([self class]));
    [self stopPlayAudioSession];
    
    [self.timer invalidate];
}

- (void)appDidEnterBackground {
    NSLog(@"%@ appDidEnterBackground",NSStringFromClass([self class]));
    [self startPlayAudioSession];
    
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(applyToSystemForMoreTime) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantPast]];
}


/// 创建音乐播放器
- (void)creatAVAudioSessionObject{
   //设置后台模式和锁屏模式下依然能够播放
   [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
   [[AVAudioSession sharedInstance] setActive: YES error: nil];
   //初始化音频播放器
   NSError *playerError;
   NSURL *urlSound = [[NSURL alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"RunInBackground" ofType:@"mp3"]];
   _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlSound error:&playerError];
   _audioPlayer.numberOfLoops = -1;//无限播放
   _audioPlayer.volume = 0;
}

/// 开始播放声音
- (void)startPlayAudioSession{
    NSLog(@"%@ startPlayAudioSession",NSStringFromClass([self class]));
   [_audioPlayer play];
}

/// 停止播放声音
- (void)stopPlayAudioSession{
    NSLog(@"%@ stopPlayAudioSession",NSStringFromClass([self class]));
   [_audioPlayer stop];
}

 
 
#pragma mark - 定时器设置判断后台保活时间，如果将要被后台杀死，重新唤醒
- (void)applyToSystemForMoreTime {
    if ([UIApplication sharedApplication].backgroundTimeRemaining < 30.0) {//如果剩余时间小于30秒
        [[UIApplication sharedApplication] endBackgroundTask:self.self.backgrounTask];
        self.backgrounTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:self.self.backgrounTask];
            self.backgrounTask = UIBackgroundTaskInvalid;
        }];
    }
}


@end

