Sound causing game to lag in swift sprite kit game?

痞子三分冷 提交于 2019-12-12 03:09:13

问题


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?


回答1:


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()
})


来源:https://stackoverflow.com/questions/41180669/sound-causing-game-to-lag-in-swift-sprite-kit-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!