如何在Swift中为这个动作创建一个循环?



我在xcode中制作了一个应用程序,用按钮振动,但我想在振动期间添加一定持续时间的间隙。我正在使用AudioServicesPlaySystemSound(kSystemSoundID_Vibrate),我想在振动发生时添加间隙。然后添加一个3秒的哔声,并使用一个循环来重复这个动作。这是我目前得到的。我如何创建一个循环?我正在用iphone 7 plus进行测试。

class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sound = Bundle.main.path(forResource: "beep", ofType: "mp3")
do{
// initialized it with URL created above
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound!))
}
catch{
print(error)
}
}
@IBAction func PressMe(_ sender: Any) {
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
for _ in 1...6 {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
Thread.sleep(forTimeInterval: 0.002)
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.audioPlayer.play()
}

}
}
}

就像这样…

play
play a sound
timer 2 seconds call gap
gap 
stop playing the sound
timer 2 seconds call play

最新更新