简体   繁体   中英

How do I create a loop for this action in Swift?

I am made an app in xcode that vibrates with a button but i would like to add gaps of a certain duration during the vibration. I am using AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) and I would like to add gaps while the vibration is occuring. Then add a beep for 3 sec and use a loop to repeat this action. This is what I have so far. How do I create a loop? I am testing using an 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()
            }
            
    }
    }
}

It's just like this..

play
  play a sound
  timer 2 seconds call gap

gap 
  stop playing the sound
  timer 2 seconds call play

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM