SWIFT触摸屏幕时如何播放声音 [英] SWIFT how to play sound when screen is touched

查看:132
本文介绍了SWIFT触摸屏幕时如何播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当贴上屏幕时,如何播放声音?这是我现在拥有的代码,在这里检查屏幕是否被触摸,然后执行某些操作……

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

        }

    }
}

推荐答案

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

这篇关于SWIFT触摸屏幕时如何播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆