2015-07-03 39 views
12

我有一個AVAudioPlayer實例,加載內存中的聲音audioPlayer.prepareToPlay(),然後在幾個開始播放它之後。我有一個問題,在進入後臺大約十分鐘後,它從內存泄漏,我沒有準備好。在那之後的幾個小時,我沒有能力再次運行prepareToPlay()。如何長時間將預加載的聲音留在內存中?我準備聲音applicationDidFinishLaunchingWithOptions方法播放:AVAudioPlayer預加載聲音從內存泄漏

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("sound", ofType:"mp3") 
     let fileData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil) 
     var error:NSError? 

     self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error) 

     self!.audioPlayer?.numberOfLoops = -1 

     self!.audioPlayer?.delegate = self 

     if (self?.audioPlayer?.prepareToPlay() != false) { 
      println("Successfully prepared for playing") 
     } else { 
      println("Failed to prepare for playing") 
     } 
    }) 

然後在didReceiveRemoteNotification我想在後臺播放:self.audioPlayer?.play(),它回報true。可能它有效,但大約10-20分鐘後不起作用。並注意.play()現在返回false

  1. 是否有禁用ARC(自動引用計數)釋放感和dealloc的audioPlayer手動?

  2. 也許我需要使用較低級別的API,如OpenAL?但是我不會使用它,因爲它在iOS 9中不推薦使用,後面我將需要重寫它,而不使用OpenAL

  3. 還有什麼想法?也許我需要使用Audio UnitsRemoteIO?如果它能工作,請提供一些例子。

  4. 也許有像ObjectAL第三方框架 - 一個容易實現的OpenAL。據我所知它是可用在IOS 9

這些方法都只是我的假設。但他們的主要問題仍然是一樣的:這些方法會從後臺工作嗎?

+0

嘗試此鏈接? http://stackoverflow.com/questions/12498015/leak-from-nsurl-and-avaudioplayer-using-arc –

+0

它看起來不像是答案 –

+0

禁用ARC:http://stackoverflow.com/questions/6646052/how -can-i-disable-arc-for-one-file-in-a-project – d4Rk

回答

2

您應該關閉ARC。當你輸入背景時,如果你不使用它,它將被釋放。在Swift中創建AVAudioPlayer爲Unmanaged<T>對象。