0
votes

I am trying to implement a xylophone where I want to play different sounds on tap of different buttons which I merged it to one IBAction function and have differentiated with different tags.

@IBAction func keysPressed(_ sender: UIButton) {
}

I am importing AVFoundation but not getting the exact function to call to play sounds

I need a function which I can call in each If else statement differentiating buttons with tags to play sounds.

1
Possible duplicate of How to play a sound using Swift? - Rocky

1 Answers

0
votes

Assuming this is a question on how to get different buttons to play different sounds, you could subclass UIButton to include a field for tracking which note it is, and call the correct function based on that.

class XyloKey: UIButton {
    var note: String
}

And then in your view controller:

let key = XyloKey()
key.note = "C5"
key.addTarget(self, action: #selector(playNote(_:)), for: .touchUpInside)

And assuming you name your files by note name (e.g. "note_C5.mp3").

func playNote(_ sender: XyloKey) {
    let url = NSBundle.mainBundle().URLForResource("note_\(sender.note)", withExtension: "mp3")
    playSound(url)
}

Where playSound plays the sound of the passed file. See the link passed in the flag above for details.