Created
July 12, 2015 18:46
-
-
Save ainoya/a2c1cd026ad5d695e406 to your computer and use it in GitHub Desktop.
Swift Extensions for SKAction.playSoundFileNamed() with custom volume
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// reference: https://github.com/pepelkod/iOS-Examples/blob/master/PlaySoundWithVolume/PlaySoundWithVolumeAction.m | |
import SpriteKit | |
public extension SKAction { | |
public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction { | |
let nameOnly = fileName.stringByDeletingPathExtension | |
let fileExt = fileName.pathExtension | |
let soundPath = NSBundle.mainBundle().URLForResource(nameOnly, withExtension: fileExt) | |
var error:NSError? | |
let player: AVAudioPlayer = AVAudioPlayer(contentsOfURL: soundPath, error: &error) | |
player.volume = atVolume | |
let playAction: SKAction = SKAction.runBlock { () -> Void in | |
player.play() | |
} | |
if(waitForCompletion){ | |
let waitAction = SKAction.waitForDuration(player.duration) | |
let groupAction: SKAction = SKAction.group([playAction, waitAction]) | |
return groupAction | |
} | |
return playAction | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 4.1 :