2015-06-28 467 views
0

我需要在用戶關閉應用程序時開始播放聲音。我用applicationDidEnterBackground方法。那就是:iOS:從背景開始播放聲音

func applicationDidEnterBackground(application: UIApplication) { 
    let dispatchQueue = 
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 

    dispatch_async(dispatchQueue, {[weak self] in 

     var audioSessionError: NSError? 
     let audioSession = AVAudioSession.sharedInstance() 
     NSNotificationCenter.defaultCenter().addObserver(self!, 
      selector: "handleInterruption:", 
      name: AVAudioSessionInterruptionNotification, 
      object: nil) 

     audioSession.setActive(true, error: nil) 

     if audioSession.setCategory(AVAudioSessionCategoryPlayback, 
      error: &audioSessionError){ 
       println("Successfully set the audio session") 
     } else { 
      println("Could not set the audio session") 
     } 

     let filePath = NSBundle.mainBundle().pathForResource("MySong", 
      ofType:"mp3") 

     let fileData = NSData(contentsOfFile: filePath!, 
      options: .DataReadingMappedIfSafe, 
      error: nil) 

     var error:NSError? 

     /* Start the audio player */ 
     self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error) 

     /* Did we get an instance of AVAudioPlayer? */ 
     if let theAudioPlayer = self!.audioPlayer{ 
      theAudioPlayer.delegate = self; 
      if theAudioPlayer.prepareToPlay() && 
       theAudioPlayer.play(){ 
        println("Successfully started playing") 
      } else { 
       println("Failed to play") 
      } 
     } else { 
      /* Handle the failure of instantiating the audio player */ 
     } 
     }) 

} 
func handleInterruption(notification: NSNotification){ 
/* Audio Session is interrupted. The player will be paused here */ 

let interruptionTypeAsObject = 
notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber 

let interruptionType = AVAudioSessionInterruptionType(rawValue: 
    interruptionTypeAsObject.unsignedLongValue) 

if let type = interruptionType{ 
    if type == .Ended{ 

    /* resume the audio if needed */ 

    } 
} 

} 

FUNC audioPlayerDidFinishPlaying(玩家:AVAudioPlayer! 成功標誌:布爾){

println("Finished playing the song") 

    /* The flag parameter tells us if the playback was successfully 
    finished or not */ 
    if player == audioPlayer{ 
    audioPlayer = nil 
    } 
    } 

它不工作。調試後,我看到theAudioPlayer.play()返回false。如果我在applicationDidFinishLaunching中運行此代碼,它會播放聲音。我添加了背景模式App plays audio or streams audio/video using AirPlay到我的Info.plist這裏有什麼問題?

+0

你需要一個UIBackgroundTaskIdentifier – Woodstock

+0

好的,請舉例說明。 –

+0

用Swift示例查看我的更新回答。 – Woodstock

回答

0

在一個非常基本的水平有三個先決條件您的應用程序應滿足在後臺播放音頻:

  • 音樂必須在目標功能被打
  • 設置「背景模式」的音頻。

  • 對於基本播放,初始化您的音頻會話,並將您的音頻會話類別設置爲AVAudioSessionCategoryPlayback。如果你不這樣做,你會得到默認行爲。

您還應該配置您的應用程序在音頻輸出

  • 變化做出反應
  • 音頻會話中斷(如電話)
  • 遠程控制事件(通過控制中心,或鎖屏)

退房this Swift的例子。