I've got a simple xylophone app I'm working with. When I try to tap a button several times in quick succession, a sound only plays for the first tap. Is there a way to decrease the response time required to play the sound?
Also, I'd like to be able to tap two or three buttons at once to play chords. How would I go about doing that?
I ran across this tutorial, is a UIGestureRecognizer the right approach?
Here's my code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func keyPressed(_ sender: UIButton) {
let soundName: String = sender.currentTitle!
sender.layer.removeAllAnimations()
playSound(note: soundName)
UIView.animate(withDuration: 0.2, delay: 0,
options: [],
animations: {
sender.alpha = 0.5
}, completion: { _ in
sender.alpha = 1
})
}
func playSound(note: String) {
let url = Bundle.main.url(forResource: note, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}