AVAudioPlayer和SKAction.playSoundFileNamed(...)导致内存泄漏

问题描述 投票:2回答:1

我的游戏基本完成了。检查Xcode中是否有泄漏。发现我每次玩游戏时泄漏大约0.3 MB。然后去了仪器,看着持久的数据。

罪魁祸首1:

SKTexture被称为很多,但没有持续增长

罪魁祸首2:

希望我记得确切的语法,它就像是AudioSource,并且在调用这一行时发生了:SKAction.playSoundFileNamed(...)

所以我进入了游戏的“设置”页面并关闭了声音。再次测试内存使用情况并且稳定。还意识到AVAudioPlayer正在泄漏,因为声音效果和主题贯穿不同的机制。

我尝试将AVAudioPlayer的实例设置为var backgroundAudio:AVAudioPlayer!,在关闭时将其设置为nil,这被声明为类变量,但这并没有帮助。

在一些强大的参考周期下,是否有一把巨大的锤子可以用来清理音频源?调用showPhysics时,我也遇到了GameViewController的问题。我认为我的问题可能是游戏的结构。主菜单调用视图和场景,因此您在场景中有一个场景。级别场景的实例似乎正在正确释放,但是留下了一些阴暗的音频错误。有解决方案吗

xcode swift memory-leaks avaudioplayer skaction
1个回答
2
投票

你应该使用SKAudioNode实例来避免内存泄漏,SKAction.playSoundFileNamed已经知道这个问题已经有一段时间了,它还没有打补丁。做这样的事情(在SKScene内):

// initiating the SKAudioNode Instance:
let soundNode = SKAudioNode(fileNamed: "mySound")
audioNode.autoplayLooped = false    

// initiating audio's duration SKAction:
let soundDuration : TimeInterval = 2 // For a 2 seconds sound!
let waitToFinish = SKAction.wait(forDuration: soundDuration)

// adding the SKAudioNode instance to the SKScene:
self.addChild(audioNode)

// running the actions:
audioNode.run(SKAction.sequence([.play(), waitToFinish]), completion: {
// Removes the SKAudioNode from the SKScene to free the memory:
    audioNode.removeFromParent()
})

或者你可以在Github上看看我的GameAudioPlayer课程,因为在这种情况下它完全符合你的要求。它处理SKAudioNodes并避免内存泄漏,您还可以在播放之前加载声音资源:https://github.com/ThiagoAM/Game-Audio-Player

我希望能帮到你!祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.