1. 程式人生 > >IOS後臺播放音樂

IOS後臺播放音樂

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代碼 技術分享
  1. #import <AVFoundation/AVFoundation.h>

定義播放器變量:

Java代碼 技術分享
  1. AVAudioPlayer *player;
  2. @property (strong, nonatomic) AVAudioPlayer *player;

自定義播放方法:

Java代碼 技術分享
  1. -(void)playSound{
  2. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
  3. [[AVAudioSession sharedInstance] setActive: YES error: nil];
  4. NSString *soundFilePath =
  5. [[NSBundle mainBundle] pathForResource: @"sound" ofType: @"mp3"];
  6. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
  7. self.player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
  8. [fileURL release];
  9. [player play];
  10. [player setDelegate: self];
  11. }

按Home鍵暫停播放(AppDelegate.m):

Java代碼 技術分享
  1. - (void)applicationDidEnterBackground:(UIApplication *)application
  2. {
  3. if (self.player.playing) {
  4. [self.player pause];
  5. }
  6. }

運行軟件繼續播放(AppDelegate.m):

Java代碼 技術分享
  1. - (void)applicationWillEnterForeground:(UIApplication *)application
  2. {
  3. if(self.player.playing == NO){
  4. [self.player play];
  5. }
  6. }
Java代碼 技術分享
  1. 模擬器可以測試!

IOS後臺播放音樂