gpt4 book ai didi

swift - 如何在tableview中的不同按钮中播放不同的声音

转载 作者:行者123 更新时间:2023-11-30 12:54:00 26 4
gpt4 key购买 nike

当我点击表格 View 单元格中的不同按钮时,我想播放不同的声音。现在,当我点击每个按钮时,它们都会播放相同的音频文件。当我点击不同的按钮时,如何告诉我的应用程序播放不同的音频文件。

这是我的代码

import UIKit
import AVFoundation

class ViewController6: UIViewController, UITableViewDataSource, UITableViewDelegate {


var player = AVQueuePlayer()



@IBOutlet var tableView: UITableView!

//Array of Rifles

var arrayOfRifles = ["AK47", "AUGA1", "FAMAS", "G36K", "K1A", "K2", "M4A1", "M4Silencer", "M16", "M60", "MicroGALIL", "QBZ95", "RPK", "ScarHeavy", "Scarlight", "SG552", "TAR21", "Tommy", "Type89", "XM8"]
var buttonDataRifles = ["AK47", "AUGA1", "FAMAS", "G36K", "K1A", "K2", "M4A1", "M4Silencer", "M16", "M60", "MicroGALIL", "QBZ95", "RPK", "ScarHeavy", "Scarlight", "SG552", "TAR21", "Tommy", "Type89", "XM8"]
var soundArrayRifles = ["AK47", "AUGA1", "FAMAS", "G36K", "K1A", "K2", "M4A1", "M4Silencer", "M16", "M60", "MicroGALIL", "QBZ95", "RPK", "ScarHeavy", "Scarlight", "SG552", "TAR21", "Tommy", "Type89", "XM8"]

var audioPlayer: AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


//Functions for tableView

//Cell - For Rifles

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (arrayOfRifles.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell6 = tableView.dequeueReusableCell(withIdentifier: "cell6", for: indexPath) as! ViewControllerTableViewCell6

cell6.myImage.image = UIImage(named: arrayOfRifles[indexPath.row] + ".jpg")
cell6.myButton.setTitle(buttonDataRifles[indexPath.row], for: UIControlState.normal)
cell6.myButton.tag = indexPath.row
cell6.myButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
return cell6
}


@IBAction func buttonAction(_ sender: UIButton) {

if let url = Bundle.main.url(forResource: "AK47", withExtension: "mp3") {
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()

}

}
}

最佳答案

if let url = Bundle.main.url(forResource: soundArrayRifles[sender.tag], withExtension: "mp3") {
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()

}

试试这个。这应该可以解决它。

关于swift - 如何在tableview中的不同按钮中播放不同的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633761/

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