Поскольку вы хотите чередовать звук при каждом воспроизведении внутри playWith
, вам необходимо иметь два аудиопроигрывателя, по одному для каждого звука.
Затем чередуйте то, что вы проигрываете, исходя из количества.
class ViewController: UIViewController {
@IBOutlet weak var whiste: UIImageView!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var textfield2: UITextField!
var arrPlayer: [AVAudioPlayer] = []
var playerA: AVAudioPlayer!
var playerB: AVAudioPlayer!
var judo = 0
@IBAction func i() {
let alertSoundA = Bundle.main.url(forResource: "regularWHistle", withExtension: "wav")!
let alertSoundB = Bundle.main.url(forResource: "otherWHistle", withExtension: "wav")!
do {
playerA = try AVAudioPlayer(contentsOf: alertSoundA)
playerB = try AVAudioPlayer(contentsOf: alertSoundB)
} 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))
}}
func playWith(repeatCount: Int) {
var timeInterval = 0.36
if let textValue = self.textfield2.text, let inputNumber = Double(textValue), inputNumber > 0 {
timeInterval = inputNumber
}
var count = 0
let timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true, block: { (timer) in
print(count)
if count != repeatCount {
let player = count % 2 == 0 ? playerA : playerB
player.play()
count += 1
} else {
timer.invalidate()
}
})
timer.fire()
}
}