首页 > 代码库 > iOS 实现后台 播放音乐声音 AVAudioPlayer
iOS 实现后台 播放音乐声音 AVAudioPlayer
1、步骤一:在Info.plist中,添加"Required background modes"键,value为:App plays audio
或者:
步骤二:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: &setCategoryErr];
[[AVAudioSession sharedInstance]
setActive: YES
error: &activationErr];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
步骤三:将以下代码添加到appDelegate文件中的- (void)applicationDidEnterBackground:(UIApplication *)application函数,也可添加到在具体类中注册的应用进入后台后的通知方法
- (void)applicationDidEnterBackground:(UIApplication *)application{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
接下来就是在播放页面进行播放了:
先加入代理:AVAudioPlayerDelegate
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #703daa } span.s1 { }</style>//从budle路径下读取音频文件 这个文件名是你的歌曲名字,mp3是你的音频格式 NSString *string = [[NSBundle mainBundle] pathForResource:@"has_consult" ofType:@"mp3"]; //把音频文件转换成url格式 NSURL *url = [NSURL fileURLWithPath:string]; //初始化音频类 并且添加播放文件 NSError *error; avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; //设置初始音量大小 // avAudioPlayer.volume = 1; //设置音乐播放次数 -1为一直循环 avAudioPlayer.numberOfLoops = -1; //预播放 [avAudioPlayer prepareToPlay]; NSLog(@"%ld",(long)error.code); //播放 -(void)play{ [avAudioPlayer play]; } //停止 -(void)stop{ avAudioPlayer.currentTime = 0; //当前播放时间设置为0 [avAudioPlayer stop]; }
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #703daa } span.s1 { }</style>
iOS 实现后台 播放音乐声音 AVAudioPlayer