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