swiftxcodeavaudioengineavaudioplayernode

Swift 3: Quickly playing sounds on AVAudioPlayerNode


I'm making a basic game and I'm trying to make hit sounds for it. I've got them to play at different pitches with help from Rhythmic Fistman, but now I have a new problem - it lags if I try playing them very quickly. This may not seem like a big problem, but in the game I'm developing, whenever you move your finger there's a chance it can make a hit sound, so it gets laggy quite fast, especially with multitouch.

Currently I have two nodes for two channels in an AVAudioEngine so I can play two hitsounds at once, and I'm using this to stop one of these nodes so it can play a new sound:

if playerNode.isPlaying {
    playerNode.stop()
    playerNode.play()
}
playerNode.scheduleFile(file, at: nil, completionHandler: nil)

The problem with this is that isPlaying always returns true no matter if a sound is actually playing or not since it seems to only return false if you do playerNode.stop(), and it is very laggy for some reason, in fact it's less laggy to play a ton of hitsounds one after the other.

I thought an easy solution would be instead of resetting the node, to just not play the hitsound, but since isPlaying always returns true I can't do this. Is there a faster way to make the audio node play the sound?


Solution

  • Seems scheduleBuffer is what I needed after all