Use textfield to create intervals between sounds being played

This code below plays a sound for a length of time listed in textField. What I would like to add to this code is have another textfield, “textfield2” be used to list the interval time amount. Right now the time interval is 0.36 I would like it to be replaced with whatever int is in textfield2.

   import UIKit
   import AVFoundation

class ViewController: UIViewController {

 @IBOutlet weak var textField: UITextField!
     @IBOutlet weak var textField2: UITextField!
   var player = AVAudioPlayer()
   var timer = Timer()
    var count: Int = 0



 @IBAction func playAction(_ sender: Any) {

let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "stereo", ofType: "wav")!)

do {
    player = try AVAudioPlayer(contentsOf: alertSound)
} catch {
    print("No sound found by URL")
}

if let textValue = self.textField.text, let inputNumber = Int(textValue), inputNumber > 0 {
    playWith(repeatCount: inputNumber)
} else {
    let alert = UIAlertController(title: "Alert", message: "Please enter number.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
}
   }
   func playWith(repeatCount: Int) {

player.play()
self.timer = Timer.scheduledTimer(withTimeInterval: 0.36, repeats: true, block: { (timer) in
    self.count += 1
    print(self.count)
    if self.count != repeatCount {
        self.player.play()
    } else {
        self.count  = 0
        self.player.stop()
        self.timer.invalidate()
    }
   })
     }
     }

func playWith(repeatCount: Int) {

    var timeInterval = 0.36
    if let textValue = self.textField2.text, let inputNumber = Double(textValue), inputNumber > 0 {
        timeInterval = inputNumber
    }

    player.play()
    self.timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { (timer) in
        self.count += 1
        print(self.count)
        if self.count != repeatCount {
            self.player.play()
        } else {
            self.count  = 0
            self.player.stop()
            self.timer.invalidate()
        }
    })
}

This topic was automatically closed after 166 days. New replies are no longer allowed.