Usually I prefer to use SKAction.playSoundWithFile in my games, but this one has a limitation, no volume setting. So, with this extension you can solve this disadvantage:
public extension SKAction { public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction { let nameOnly = (fileName as NSString).stringByDeletingPathExtension let fileExt = (fileName as NSString).pathExtension let soundPath = NSBundle.mainBundle().URLForResource(nameOnly, withExtension: fileExt) var player: AVAudioPlayer! = AVAudioPlayer() do { player = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil) } catch let error as 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 } }
Using
self.runAction(SKAction.playSoundFileNamed("diamondCollect.wav", atVolume:0.5, waitForCompletion: true))
source share