我有一个AVAudioPlayer实例,用audioPlayer.prepareToPlay()加载内存中的声音,然后几次开始播放它.我有一个问题,在进入背景后大约十分钟内,它从内存泄漏,我没有准备好.之后喂了几个小时,我没有能力再次运行prepareToPlay().如何将这个预加载的声音留在记忆中长期?我正在准备声音在applicationDidFinishLaunchingWithOptions方法中播放:
- 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.
>有意义的是禁用ARC(自动引用计数)手动释放和释放audioPlayer?
>也许我需要使用较低级别的API,如OpenAL?然而,我不会使用它,因为它在iOS 9和更高版本中被弃用,我将需要重写它没有OpenAL.
>还有什么想法?也许我需要使用AudioIO AudioIO?如果可以,请提供一些例子.
>也许有像ObjectAL
这样的第三方框架 – 一个简单的OpenAL实现.据我所知,它在iOS 9中可用.
解决方法
你应该禁用ARC.当您输入背景音乐时,如果您不使用它,它将被释放.在Swift中,将AVAudioPlayer创建为非托管< T>目的.