如果打回來了,就自認倒霉吧
制作無聲音頻。
@interface AppDelegate ()
{
NSInteger count;
}
@property(strong, nonatomic)NSTimer *mTimer;
@property(assign, nonatomic)UIBackgroundTaskIdentifier backIden;
- (void)applicationDidEnterBackground:(UIApplication *)application {
_mTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_mTimer forMode:NSRunLoopCommonModes];
[self beginTask];
}
//計時
-(void)countAction{
NSLog(@"%li",count++);
}
//申請后台
-(void)beginTask
{
NSLog(@"begin=============");
_backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"將要掛起=============");
[self endBack];
}];
}
//注銷后台
-(void)endBack
{
NSLog(@"end=============");
[[UIApplication sharedApplication] endBackgroundTask:_backIden];
_backIden = UIBackgroundTaskInvalid;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[self endBack];
}
#import <AVFoundation/AVFoundation.h>
@property(strong, nonatomic)AVAudioPlayer *mPlayer;
@property(assign, nonatomic)CGFloat mCount;
- (void)viewDidLoad {
[super viewDidLoad];
_mCount = 0;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(countTime) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)countTime{
_mCount+=10;
NSLog(@"%f",_mCount);
if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 60.) {//當剩余時間小於60時,開如播放音樂,並用這個假前台狀態再次申請后台
NSLog(@"播放%@",[NSThread currentThread]);
[self playMusic];
//申請后台
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"我要掛起了");
}];
}
}
-(void)playMusic{
//1.音頻文件的url路徑,實際開發中,用無聲音樂
NSURL *url=[[NSBundle mainBundle]URLForResource:@"wusheng.mp3" withExtension:Nil];
//2.創建播放器(注意:一個AVAudioPlayer只能播放一個url)
_mPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
//3.緩沖
[_mPlayer prepareToPlay];
_mPlayer.numberOfLoops = -1;
//4.播放
[_mPlayer play];
}