Search code examples
iosswiftavaudioplayer

Add sound for each button


I'm making an app to get a name from the user and then choose a thumbnail (and it'll play a sound). Problem is I couldn't get it to play different sounds for each button. What it plays is the last one that I keyed the value in (in this case, avengers). I started Swift last week and I don't know much about the language. I google most of the time. Here's my code. Thanks in advance.

import UIKit
import AVFoundation

class ImagesViewController: UIViewController, AVAudioPlayerDelegate {

    var audioPlayer: AVAudioPlayer?

    @IBAction func antman(sender: AnyObject) {
        audioPlayer!.play()
    }
    @IBAction func avengers(sender: AnyObject) {
        audioPlayer!.play()
    }

    func selectSound(alertSound: String, sound: String)  {

        var alertSound: NSURL = NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "mp3")!)

        var error: NSError?
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
        }
        catch var error1 as NSError {
            error = error1
            audioPlayer = nil
        }

        audioPlayer!.delegate = self
        audioPlayer!.prepareToPlay()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        selectSound("1", sound: "antman")
        selectSound("2", sound: "avengers")
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let newVC: Results = segue.destinationViewController as! Results
        print("xxx ,%s", segue.identifier)

        newVC.receivedFirstName = segue.identifier!
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Solution

  • You can do something like:

        @IBAction func antman(sender: AnyObject) {
            selectSound("1", sound: "antman")
            audioPlayer!.play()
        }
        @IBAction func avengers(sender: AnyObject) {
            selectSound("2", sound: "avengers")
            audioPlayer!.play()
        }