Use AVAudioPlayer to play sound effects

by

Right now I am at the stage where I am writing foundation to manage my sound effects and background music for my upcoming game. I found two most popular way to play sound effects in SpriteKit:

  • SKAction
  • AVAudioPlayer

After using both I found myself more flexible and comfortable with AVAudioPlayer for following reasons that I am grabbing from Apple’s documentation but it helds true:

Using an audio player you can:
  • Play sounds of any duration
  • Play sounds from files or memory buffers
  • Loop sounds
  • Play multiple sounds simultaneously, one sound per audio player, with precise synchronization
  • Control relative playback level, stereo positioning, and playback rate for each sound you are playing
  • Seek to a particular point in a sound file, which supports such application features as fast forward and rewind
  • Obtain data you can use for playback-level metering

You might also like: Sort an array of string containing numbers

You might also like: MFMessageComposeViewController shows blank white screen issue

My sound effects are wav files. I have stored them in .xcassets folder as a “data set” where I find management more flexible. I will show how to play sound file stored in .xcassets with AVAudioPlayer

func playSoundEffect() {
    if let asset = NSDataAsset(name:“soundasset”){
        do {
            // Use NSDataAsset’s data property to access the audio file stored in Sound.
            soundEffect = try AVAudioPlayer(data:asset.data, fileTypeHint:“wav”)
            // Play the above sound file.
            soundEffect?.play()
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

More Articles

Recommended posts