微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Swift 中为此操作创建循环?

如何解决如何在 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。