Giovanni Portogallo Giovanni Portogallo - 27 days ago 4x
Swift Question

Need help adding an audio file to a button in swift

can anyone help me get this to work I am a noob programer and I could not find a way to do this.

Code below

import UIKit

class ViewController: UIViewController {

@IBAction func pistolButton(sender: AnyObject) {


override func viewDidLoad() { // I want my audio file to play when button is tapped


override func didReceiveMemoryWarning() {



First drag your sound to your project and choose to copy for your destination if needed and check "add to target" to your app. Create a function to play your sound and you need also to add import AVFoundation at the beginning of your code as bellow:

import AVFoundation

let beepSoundURL =  NSBundle.mainBundle().URLForResource("beep", withExtension: "aif")!
var beepPlayer = AVAudioPlayer()
func playMySound(){
   beepPlayer = AVAudioPlayer(contentsOfURL: beepSoundURL, error: nil)

@IBAction func pistolButton(sender: AnyObject) {