IOS后台播放音乐
Posted ios4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS后台播放音乐相关的知识,希望对你有一定的参考价值。
http://www.apple.com.cn/developer/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/AudioandVideoTechnologies/AudioandVideoTechnologies.html#//apple_ref/doc/uid/TP40007072-CH19-SW32
1.首先在工程中导入播放音乐所使用的框架:AV Foundation框架
2.在项目中添加代码:
导入框架头文件:
- #import <AVFoundation/AVFoundation.h>
定义播放器变量:
- AVAudioPlayer *player;
- @property (strong, nonatomic) AVAudioPlayer *player;
自定义播放方法:
- -(void)playSound{
- [[AVAudiosession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
- [[AVAudioSession sharedInstance] setActive: YES error: nil];
- NSString *soundFilePath =
- [[NSBundle mainBundle] pathForResource: @"sound" ofType: @"mp3"];
- NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
- self.player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
- [fileURL release];
- [player play];
- [player setDelegate: self];
- }
按Home键暂停播放(AppDelegate.m):
- - (void)applicationDidEnterBackground:(UIApplication *)application
- {
- if (self.player.playing) {
- [self.player pause];
- }
- }
运行软件继续播放(AppDelegate.m):
- - (void)applicationWillEnterForeground:(UIApplication *)application
- {
- if(self.player.playing == NO){
- [self.player play];
- }
- }
- 模拟器可以测试!
以上是关于IOS后台播放音乐的主要内容,如果未能解决你的问题,请参考以下文章