niX
niX

Reputation: 167

Sound causing game to lag in swift sprite kit game?

New code

class SceneTwo: SKScene, SKPhysicsContactDelegate {

   let flap = SKAction.playSoundFileNamed("flap.caf", waitForCompletion: false)

   let whack = SKAction.playSoundFileNamed("whack.caf", waitForCompletion: false)

   let tap = SKAction.playSoundFileNamed("tap.caf", waitForCompletion: false)

Then I simply have put

run(tap) run(flap) etc where necessary..

Hi just wondering if I am using the correct coding to play sounds in my game. For some context my game is similar to Flappy bird. One sound is played each time the screen is touched (when the bird has impulse upwards) the second sound is when the bird collects a coin in between each wall.

I have noticed that both of these sounds are causing my game to lag.

Below is my relative sound code for the game.

import AVFoundation   

   var flap: AVAudioPlayer?

   var tap: AVAudioPlayer?

override func didMove(to view: SKView) {
    tap?.prepareToPlay()


    flap?.prepareToPlay()


func playFlap() {
    let url = Bundle.main.url(forResource: "flap", withExtension: "caf")!

    do {
        flap = try AVAudioPlayer(contentsOf: url)
        guard let flap = flap else { return }


        flap.play()
    } catch let error {
        print(error.localizedDescription)
    }
}


func playTap() {
    let url = Bundle.main.url(forResource: "tap", withExtension: "caf")!

    do {
        tap = try AVAudioPlayer(contentsOf: url)
        guard let tap = tap else { return }


        tap.play()
    } catch let error {
        print(error.localizedDescription)
    }
}

After this I have simply

playTap()
playFlap()

to where they are needed.

The sound is clear it just seems to make my spawning walls jump a little bit when the sound is made. Is there something I am doing that is wrong?

Upvotes: 0

Views: 506

Answers (1)

Munahil
Munahil

Reputation: 2419

You are getting lag because you are not preloading the sound files. You can preload them at App Launch, and then when you need just play them. For reference look into this stackoverflow's post

And if you still face the same issue then you can add sound in background queue, as demostrated here

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    audioPlayer.play()
})

Upvotes: 1

Related Questions