为每个按钮添加声音

Add sound for each button

我正在制作一个应用程序来从用户那里获取一个名字,然后选择一个缩略图(它会播放声音)。问题是我无法让它为每个按钮播放不同的声音。它播放的是我键入值的最后一个(在本例中为复仇者联盟)。我上周开始 Swift,我对这门语言了解不多。大多数时候我 google。这是我的代码。提前致谢。

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.
    }
    */

}

您可以这样做:

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