Skip to content

Instantly share code, notes, and snippets.

@ainoya
Created July 12, 2015 18:46
Show Gist options
  • Save ainoya/a2c1cd026ad5d695e406 to your computer and use it in GitHub Desktop.
Save ainoya/a2c1cd026ad5d695e406 to your computer and use it in GitHub Desktop.
Swift Extensions for SKAction.playSoundFileNamed() with custom volume
// 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
}
}
@Coder-ACJHP
Copy link

Updated for Swift 4.1 :

`public extension SKAction {

    public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction {
    
    let nameOnly = URL(fileURLWithPath: fileName).deletingPathExtension().lastPathComponent
    let fileExt  = fileName.pathExtension
    
    let soundPath = Bundle.main.url(forResource: nameOnly, withExtension: fileExt)
    
    var player: AVAudioPlayer!
    do {
       player = try AVAudioPlayer(contentsOf: soundPath!)
    } catch {
        debugPrint("Error with playing soundFile: \(error.localizedDescription)")
    }
    
    player.volume = atVolume
    
    let playAction: SKAction = SKAction.run { () -> Void in
        player.play()
    }
    
    if(waitForCompletion){
        let waitAction = SKAction.wait(forDuration: player.duration)
        let groupAction: SKAction = SKAction.group([playAction, waitAction])
        return groupAction
    }
    
    return playAction
 }
}

extension String {
    var ns: NSString {
        return self as NSString
    }
    var pathExtension: String {
        return ns.pathExtension
    }
    var lastPathComponent: String {
        return ns.lastPathComponent
    }
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment