对于ios7,苹果支持几种后台运行模式,backgroundTask,voip,后台播放音乐等,具体看官方文档就好。本文介绍依靠音乐播放来实现
#import
#import
@interface AllRuning : NSObject
@property (nonatomic, strong) AVAudioPlayer *myBackMusic;
+ (instancetype)sharedInstance;
- (void)creatVideo;
- (void)play;
- (void)pause;
@end
#import "AllRuning.h"
@implementation AllRuning
@synthesize myBackMusic;
// 声明一个静态变量
static AllRuning *sharedInstance = nil;
+ (instancetype)sharedInstance
{
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (void)creatVideo
{
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Imagine" ofType:@"mp3"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:musicPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
// 创建播放器
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
self.myBackMusic = player; //赋值给自己定义的类变量
[myBackMusic setVolume:0];
myBackMusic.numberOfLoops = -1; //设置音乐播放次数 -1为一直循环
}
- (void)play
{
[myBackMusic prepareToPlay];
[myBackMusic play]; //播放
}
- (void)pause
{
if (myBackMusic.isPlaying) {
[myBackMusic pause]; //停止
}
}
@end