我正在创建一个应用程序,以便从用户那里获取一个名称,然后选择一个缩略图(它会发出声音)。问题是我无法让它为每个按钮播放不同的声音。它所扮演的是我键入值的最后一个(在这种情况下,复仇者)。上周我开始使用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.
}
*/
}
答案 0 :(得分:0)
您可以执行以下操作:
@IBAction func antman(sender: AnyObject) {
selectSound("1", sound: "antman")
audioPlayer!.play()
}
@IBAction func avengers(sender: AnyObject) {
selectSound("2", sound: "avengers")
audioPlayer!.play()
}