gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:37:15 24 4
gpt4 key购买 nike

我的游戏基本完成了。检查 Xcode 中的泄漏。发现我每次玩游戏都会泄漏大约 0.3 MB。然后去了仪器并查看了持久数据。

罪魁祸首 1:

SKTexture,被调用了很多但没有持续增长

罪魁祸首 2:

希望我记得确切的语法,它类似于 AudioSource,并且在调用此行时发生:SKAction.playSoundFileNamed(...)

所以我转到游戏的“设置”页面并关闭了声音。再次测试内存占用,稳定。还意识到 AVAudioPlayer 正在泄漏,因为音效和主题通过不同的机制运行。

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

是否有一个巨大的锤子可以用来在某些强大的引用周期下清理音频源?当调用 showPhysics 时,我的 GameViewController 也有问题。我想我的问题可能是游戏的结构。主菜单调用 View 和场景,因此场景中有场景。关卡场景的实例似乎已正确发布,但留下了一些模糊的音频错误。有什么解决办法吗?

最佳答案

您应该使用 SKAudioNode 实例来避免内存泄漏,SKAction.playSoundFileNamed 因这个问题而为人所知已有一段时间。做这样的事情(在 SKScene 内):

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

// Initializing the audio's duration SKAction:
let soundDuration : TimeInterval = 2 // For a 2 second 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

希望对你有帮助!祝你好运!

关于xcode - AVAudioPlayer 和 SKAction.playSoundFileNamed(...) 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com