Search code examples
swiftavaudioplayer

How to make a function play different sounds in Swift


I have 10 different buttons and each button has a unique tag associated with it. All buttons are linked to the same IBAction. I have the function to play different different sounds according to the tag associated with the particular button that is clicked.

import AVFoundation

var myAudio: AVAudioPlayer!

let path = Bundle.main.path(forResource: "sound1", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
    let sound = try AVAudioPlayer(contentsOf: url)
    myAudio = sound
    sound.play()
    } catch {
        //
    }
}

Solution

  • do like

    @objc func yourbtnActionName(_ sender : UIButton){
    
        switch sender.tag {
        case 1:
            commonSoundCode(name: "sound1")
            break
        case 2:
            commonSoundCode(name: "yoursecondSoundname")
            break
        default:
            break
        }
       }
    

    then common method as

     func commonSoundCode(name: String){
        let path = Bundle.main.path(forResource: name, ofType: "wav")!
        let url = URL(fileURLWithPath: path)
        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            myAudio = sound
            sound.play()
        } catch {
            //
        }
    }
    

    option 2

    if your sound files are in the same sequence, for e.g (sound1.wav, sound2.wav......, sound10.wav) then call like

    @objc func yourbtnActionName(_ sender : UIButton){
      let path = Bundle.main.path(forResource: "sound\(sender.tag)", ofType: "wav")!
        let url = URL(fileURLWithPath: path)
        do {
            let sound = try AVAudioPlayer(contentsOf: url)
            myAudio = sound
            sound.play()
        } catch {
            //
        }
    
    }