1 Reply
      Latest reply: Jan 5, 2017 2:42 AM by eskimo RSS
      GerardoGlz Level 1 Level 1 (0 points)

        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() {





                for sound in soundFilenames {

                    do {

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

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














            override func didReceiveMemoryWarning() {





            @IBAction func buttonTapped(_ sender: UIButton) {



                let audioPlayer = audioPlayers[sender.tag]






        • Re: All my buttons play the same sound
          eskimo Apple Staff Apple Staff (6,665 points)

          I recommend you break buttonTapped(_:) up a bit.

          let tag = sender.tag
          let audioPlayer = audioPlayers[tag]

          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"