How can I play a sound file with AVFoundation in a Swift
playground
? Ideally, the file would be in a URL, not in the local drive, but that\'s not i
This works on a project I haven't tried on Playground. First drag your sound to your project and choose to copy for your destination if needed and check "add to target" to your app.
import Cocoa
import AVFoundation
var beepSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("beep", ofType: "aif")!)
func initBeep(){
beepPlayer = AVAudioPlayer(contentsOfURL: beepSound, error: nil)
beepPlayer.prepareToPlay()
}
func playBeepSound(){
beepPlayer.play()
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
initBeep()
}
@IBAction func btnPlayBeepSound(sender: AnyObject) {
playBeepSound()
}