IOS後臺播放音樂
阿新 • • 發佈:2017-05-22
har highlight 播放器 title ges round eas tro ios
IOS後臺播放音樂
博客分類:- 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];
- }
- }
- 模擬器可以測試!
IOS後臺播放音樂