swift - Game lagging when AVAudioPlayer plays -


i'm creating game user controls character jetpack. when jetpack intersects diamond, add diamond total , play sound. however, sound makes game pause tenth of second or , disrupts flow. code i'm using:

var diamondsound = nsbundle.mainbundle().urlforresource("diamondcollect", withextension: "wav")! var diamondplayer = avaudioplayer?()      class gamescene: skscene{        override func didmovetoview(view: skview) {              {                  diamondplayer = try avaudioplayer(contentsofurl: diamondsound)                  guard let player = diamondplayer else { return }                   player.preparetoplay()             } catch let error nserror {                  print(error.description)             }        } 

and later:

    override func update(currenttime: cftimeinterval) {          if character.intersectsnode(diamond){             diamondplayer?.play()             adddiamond()             diamond.removefromparent()         }      } 

also using sprite kit if matters. appreciated!

usually, prefeer use skaction.playsoundwithfile in games 1 have limitation, there no volume setting. so, whit extension can solve lack:

public extension skaction {   public class func playsoundfilenamed(filename: string, atvolume: float, waitforcompletion: bool) -> skaction {      let nameonly = (filename nsstring).stringbydeletingpathextension     let fileext  = (filename nsstring).pathextension      let soundpath = nsbundle.mainbundle().urlforresource(nameonly, withextension: fileext)       var player: avaudioplayer! = avaudioplayer()     { player = try avaudioplayer(contentsofurl: soundpath!, filetypehint: nil) }     catch let error nserror { print(error.description) }      player.volume = atvolume      let playaction: skaction = skaction.runblock { () -> void in         player.preparetoplay()         player.play()     }      if(waitforcompletion){         let waitaction = skaction.waitforduration(player.duration)         let groupaction: skaction = skaction.group([playaction, waitaction])         return groupaction     }      return playaction   } } 

usage:

self.runaction(skaction.playsoundfilenamed("diamondcollect.wav", atvolume:0.5, waitforcompletion: true)) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -