0

How do i play sound whenever screen is taped? this is a code I have now, where I check if screen has been touched and than it does some things...

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if TapsValid == true {
        Score++

        if BallRight == true {

            BallChange = false

        } else {

            BallChange = true

        }

    }
}
DaBist
  • 1
  • 1
  • 2
    Possible duplicate of [Creating and playing a sound in swift](http://stackoverflow.com/questions/24043904/creating-and-playing-a-sound-in-swift) – Grimxn Jun 23 '16 at 16:02

1 Answers1

0
import AVFoundation

/// You **must** keep reference to this...
private var audioPlayer: AVAudioPlayer!

/**
    Tap
*/
public func tapSound() -> Void
{
    let bundle: NSBundle = NSBundle(forClass: SoundMachine.self)
    if let file_url: NSURL = bundle.URLForResource("tap_sounf", withExtension:"caf")
    {
        self.playSoundFromURL(file_url)
    }
}

/**
    Reproduce un archivo de sonido que se encuentra
    en el Bundle de nuestra app

    - parameter resource_url: La URL al archivo
*/
private func playSoundFromURL(resource_url: NSURL) -> Void
{
    self.audioPlayer = try! AVAudioPlayer(contentsOfURL:resource_url)
    self.audioPlayer.prepareToPlay()
    self.audioPlayer.play()
}
Adolfo
  • 1,862
  • 13
  • 19