声音会导致游戏在快速Sprite Kit游戏中滞后吗? [英] Sound causing game to lag in swift sprite kit game?

查看:81
本文介绍了声音会导致游戏在快速Sprite Kit游戏中滞后吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新代码

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)

那我就放了

运行(点击) 运行(襟翼)等 必要的话.

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

在此之后,我简单地

playTap()
playFlap()

到需要它们的地方.

声音很清晰,听起来好像使我的产卵墙跳了一点. 我在做某事是错的吗?

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?

推荐答案

由于没有预加载声音文件,因此您会感到很滞后.您可以在应用启动时预加载它们,然后在需要时播放它们.作为参考,请查看此 stackoverflow的帖子

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

这篇关于声音会导致游戏在快速Sprite Kit游戏中滞后吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆