Using an audio clip causing a memory leak

I have a script for a game with a sprite ( SKScene) that uses audio clips from time to time. I do not want to create a new action ( SKAction) every time I need to play a short audio clip, because the sound may stutter. Therefore, I initialize the action variable with the file name and get ready to use it when necessary.

class GameScene: SKScene {
    let audioMatchAction = SKAction.playSoundFileNamed("myAudio", waitForCompletion: false)
}

Then, when I need to run this audio clip, I just use the following line of code.

self.run(audioMatchAction)

Given all circumstances, there are some signs that memory may leak when a view controller ( UIViewController) sets up a scene. So I used Allocations to find out what was going on. And he says there are two leaks pointing to the library AudioToolbox. Anyway, I changed the line above to the next.

let waitAction = SKAction.wait(forDuration: 1.0)
self.run(audioMatchAction, withKey: "audio")
self.run(waitAction, completion: {
    self.removeAction(forKey: "audio")
})

, . , SKAction . , SKAudioNode, SKAction.playSoundFileNamed. . . AVAudioPlayer. . , Allocations , , . , , ? .

UPDATE

, AVAudioPlayer, , .

class GameScene: SKScene {
    let audioURLMatch = URL(fileURLWithPath: Bundle.main.path(forResource: "myAudio", ofType: "caf")!) as NSURL
    var audioURLMatchPlayer = AVAudioPlayer()
    override func didMove(to view: SKView) {
        // audio //
        do {
            audioURLMatchPlayer = try AVAudioPlayer(contentsOf: audioURLMatch as URL)
            audioURLMatchPlayer.prepareToPlay()
        } catch let error {

        }
    }
}

enter image description here

+4
1

audioURLMatchPlayer .

var audioURLMatchPlayer: AVAudioPlayer? var audioURLMatchPlayer = AVAudioPlayer()

0

Source: https://habr.com/ru/post/1676577/


All Articles