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.在项目中添加代码:
导入框架头文件:
Java代码
- #import <AVFoundation/AVFoundation.h>
定义播放器变量:
Java代码
- AVAudioPlayer *player;
- @property (strong, nonatomic) AVAudioPlayer *player;
自定义播放方法:
Java代码
- -(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):
Java代码
- - (void)applicationDidEnterBackground:(UIApplication *)application
- {
- if (self.player.playing) {
- [self.player pause];
- }
- }
运行软件继续播放(AppDelegate.m):
Java代码
- - (void)applicationWillEnterForeground:(UIApplication *)application
- {
- if(self.player.playing == NO){
- [self.player play];
- }
- }
Java代码
- 模拟器可以测试!
时间: 2024-11-03 21:08:45