原理:
1.開啟后臺任務(wù)權(quán)限回季,播放音樂
image.png
2.app后臺后,開啟后臺任務(wù)正林,定時輪詢后臺剩余時間泡一,低于20秒時候再申請新的后臺任務(wù)
3.app回前臺后,結(jié)束后臺任務(wù)
-(void)applicationDidEnterBackground:(UIApplication *)application{
[[BackgroundTaskTool shareTool] startBackgroundTask];
}
-(void)applicationWillEnterForeground:(UIApplication *)application{
[[BackgroundTaskTool shareTool] stopBackgroundTask];
}
.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface BackgroundTaskTool : NSObject
+(instancetype)shareTool;
-(void)startBackgroundTask;
-(void)stopBackgroundTask;
@end
NS_ASSUME_NONNULL_END
.m
#import "BackgroundTaskTool.h"
#import <AVFoundation/AVFoundation.h>
///循環(huán)時間5秒查一次是否需要再次申請后臺任務(wù)
static NSInteger _circulaDuration = 5;
static BackgroundTaskTool *_sharedTool;
@interface BackgroundTaskTool()
@property (nonatomic,assign) UIBackgroundTaskIdentifier task;
///后臺播放
@property (nonatomic,strong) AVAudioPlayer *playerBack;
@property (nonatomic, strong) NSTimer *timerAD;
///用來打印測試
@property (nonatomic, strong) NSTimer *timerLog;
@property (nonatomic,assign) NSInteger count;
@end
@implementation BackgroundTaskTool{
CFRunLoopRef _runloopRef;
dispatch_queue_t _queue;
}
+ (instancetype)shareTool
{
static BackgroundTaskTool *tool = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
tool = [[self alloc] init];
});
return tool;
}
/// 重寫init方法觅廓,初始化音樂文件
- (instancetype)init {
if (self = [super init]) {
[self setupAudioSession];
_queue = dispatch_queue_create("com.audio.inBackground", NULL);
//靜音文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Silence" ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.playerBack = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[self.playerBack prepareToPlay];
// 0.0~1.0,默認為1.0
self.playerBack.volume = 0.01;
// 循環(huán)播放
self.playerBack.numberOfLoops = -1;
}
return self;
}
- (void)setupAudioSession {
// 新建AudioSession會話
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// 設(shè)置后臺播放
NSError *error = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
if (error) {
NSLog(@"Error setCategory AVAudioSession: %@", error);
}
NSLog(@"%d", audioSession.isOtherAudioPlaying);
NSError *activeSetError = nil;
// 啟動AudioSession鼻忠,如果一個前臺app正在播放音頻則可能會啟動失敗
[audioSession setActive:YES error:&activeSetError];
if (activeSetError) {
NSLog(@"Error activating AVAudioSession: %@", activeSetError);
}
}
/**
啟動后臺運行
*/
- (void)startBackgroundTask{
[self.playerBack play];
[self applyforBackgroundTask];
///確保兩個定時器同時進行
dispatch_async(_queue, ^{
self.timerLog = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(log) userInfo:nil repeats:YES];
self.timerAD = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:_circulaDuration target:self selector:@selector(startAudioPlay) userInfo:nil repeats:YES];
self->_runloopRef = CFRunLoopGetCurrent();
[[NSRunLoop currentRunLoop] addTimer:self.timerAD forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:self.timerLog forMode:NSDefaultRunLoopMode];
CFRunLoopRun();
});
}
/**
申請后臺
*/
- (void)applyforBackgroundTask{
_task =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] endBackgroundTask:self->_task];
self->_task = UIBackgroundTaskInvalid;
});
}];
}
/**
打印
*/
- (void)log{
_count = _count + 1;
NSLog(@"_count = %ld",_count);
}
/**
檢測后臺運行時間
*/
- (void)startAudioPlay{
_count = 0;
dispatch_async(dispatch_get_main_queue(), ^{
if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 20.0) {
NSLog(@"后臺快被殺死了");
[self.playerBack play];
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] endBackgroundTask:self->_task];
self->_task = UIBackgroundTaskInvalid;
});
dispatch_after(0.1, dispatch_get_main_queue(), ^{
[self applyforBackgroundTask];
});
}
else{
NSLog(@"后臺繼續(xù)活躍呢");
}///再次執(zhí)行播放器停止,后臺一直不會播放音樂文件
[self.playerBack stop];
});
}
/**
停止后臺運行
*/
- (void)stopBackgroundTask{
if (self.timerAD) {
CFRunLoopStop(_runloopRef);
[self.timerLog invalidate];
self.timerLog = nil;
// 關(guān)閉定時器即可
[self.timerAD invalidate];
self.timerAD = nil;
[self.playerBack stop];
}
if (_task) {
[[UIApplication sharedApplication] endBackgroundTask:_task];
_task = UIBackgroundTaskInvalid;
}
}
@end