0
我正在制作应用程序以从用户那里获取名称,然后选择一个缩略图(它会播放声音)。问题是我不能让它为每个按钮播放不同的声音。它所扮演的是最后一个我把价值锁定的人(在这种情况下,复仇者)。我上周开始了Swift,对语言不太了解。我大部分时间都是谷歌。这是我的代码。提前致谢。为每个按钮添加声音
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.
}
*/
}
你只需要您的视图控制器上一个'audioPlayer'属性,初始化它两次:一次为“安特曼”和第二次“复仇者“。因此,当您调用'audioPlayer!.play()'时,它会检索在'audioPlayer'中初始化的最后一个声音并播放它。您可以初始化两个独立的'AVAudioPlayer'属性,或者在按下按钮时用正确的声音初始化'AVAudioPlayer'。对于一个响应按键按压的小声音,这可能表现得足够好。 – Palpatim