【发布时间】:2015-09-21 15:23:45
【问题描述】:
我有一个 AVAudioPlayer 实例,它使用audioPlayer.prepareToPlay() 将声音加载到内存中,然后开始播放。我有一个问题,在进入后台大约十分钟后,它从内存中泄漏,我没有做好准备。在那喂食时间之后,我无法再次运行prepareToPlay()。如何将预加载的声音长期留在记忆中?我正在准备在applicationDidFinishLaunchingWithOptionsmethod 中播放声音:
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的情况下重写它。还有什么想法吗?也许我需要将
Audio Units与RemoteIO一起使用?如果可行,请提供一些示例。也许有像
ObjectAL这样的第三方框架 -OpenAL的简单实现。据我所知,它在 iOS 9 中可用。
这些方法只是我的假设。但他们的主要问题仍然是相同的:这些方法会在后台工作吗?
【问题讨论】:
-
看起来不像是答案
-
你试过这样做吗?你有解释吗?
标签: ios memory-management memory-leaks background avaudioplayer