All my buttons play the same sound

Hey! So I'm new to coding, and right now I'm trying to make a simple soundboard app on Xcode. I have 5 different sounds and 5 different buttons. I want each button to play one of those sounds. The problem is: All my buttons play the first sound. I can't find the problem. Please, help.



import UIKit

import AVFoundation

class ViewController: UIViewController {


let soundFilenames = ["sound1","sound2","sound3","sound4","sound5"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {

super.viewDidLoad()

/

/

for sound in soundFilenames {

do {

let audioPath = Bundle.main.path(forResource: sound, ofType: "wav")

let audioPlayer = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

audioPlayers.append(audioPlayer)

}

catch

{

audioPlayers.append(AVAudioPlayer())

}

}

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

/

}


@IBAction func buttonTapped(_ sender: UIButton) {

/

let audioPlayer = audioPlayers[sender.tag]

audioPlayer.play()

}


}

Replies

I recommend you break

buttonTapped(_:)
up a bit.
let tag = sender.tag
let audioPlayer = audioPlayers[tag]
audioPlayer.play()

then step through the code to see what

tag
is set to. If
tag
is correct, you need to look at how
audioPlayers
is set up. OTOH, if you
tag
is wrong then you’ll need to look at why that is.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Can you send me the code of the app so I could make it? It sounds cool and I can fix the problem so it will work. Sincerely, Jared