gpt4 book ai didi

ios - Swift - 选择不同声音时不播放不同声音

转载 作者:行者123 更新时间:2023-11-30 14:07:40 24 4
gpt4 key购买 nike

在 Swift 中,当在 TableView 中选择不同的声音时,声音的名称将添加到变量中。在不同的 View Controller 中,它应该访问变量并在按下按钮时播放声音,尽管它只是播放相同的声音。这是代码:

FirstSoundController(播放声音):

class FirstViewController: UIViewController {
var someVariable = SecondViewController()
@IBAction func activation(sender: UIButton) {
if sender.titleLabel!.text == "ACTIVATE" {
sender.setTitle("DEACTIVATE", forState: UIControlState.Normal)

var someSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(someVariable.soundSelected, ofType: "mp3")!)

audioPlayer = AVAudioPlayer(contentsOfURL: someSound, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
else {
sender.setTitle("ACTIVATE", forState: UIControlState.Normal)
audioPlayer.stop()
}
}
}

SecondViewController(显示声音表):

class SecondViewController: UIViewController, UITableViewDataSource {
var sounds = ["BananaSlap", "GlassBreaking", "scream", "WoodyWood", "LaughAndApplause", "EvilLaugh", "Grenade", "BadamTss", "BombExploding"]
var soundSelected:String?
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sounds.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel?.text = sounds[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
var soundSelected = sounds[indexPath.row]
println(soundSelected)
}

}

最佳答案

我可以立即发现您的 SecondViewController 中的错误,因为您已将 soundSelected 重新声明为函数内的局部变量,而忽略了该属性。所以,而不是:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
var soundSelected = sounds[indexPath.row]
println(soundSelected)
}

我会尝试:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
soundSelected = sounds[indexPath.row]
println(soundSelected)
}

关于ios - Swift - 选择不同声音时不播放不同声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32162382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com