2015-07-03 42 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>对象。