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];
- }
- }