SWIFT触摸屏幕时如何播放声音

时间:2016-06-23 15:56:46

标签: ios swift audio touch tap

每当录制屏幕时,我如何播放声音?这是我现在的代码,在那里我检查屏幕是否被触摸,而不是它做了一些事情......

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

    if TapsValid == true {
        Score++

        if BallRight == true {

            BallChange = false

        } else {

            BallChange = true

        }

    }
}

1 个答案:

答案 0 :(得分: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()
}