Creating and playing a sound in swift
Handy Swift extension:
import AudioToolbox
extension SystemSoundID {
static func playFileNamed(fileName: String, withExtenstion fileExtension: String) {
var sound: SystemSoundID = 0
if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) {
AudioServicesCreateSystemSoundID(soundURL, &sound)
AudioServicesPlaySystemSound(sound)
}
}
}
Then, from anywhere in your app (remember to import AudioToolbox
), you can call
SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
to play "sound.mp3"
This is similar to some other answers, but perhaps a little more "Swifty":
// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
Note that this is a trivial example reproducing the effect of the code in the question. You'll need to make sure to import AudioToolbox
, plus the general pattern for this kind of code would be to load your sounds when your app starts up, saving them in SystemSoundID
instance variables somewhere, use them throughout your app, then call AudioServicesDisposeSystemSoundID
when you're finished with them.
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}