SWIFT how to play sound when screen is touched

天涯浪子 提交于 2020-01-14 05:34:12

问题


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

        }

    }
}

回答1:


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()
}


来源:https://stackoverflow.com/questions/37996497/swift-how-to-play-sound-when-screen-is-touched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!