当我在tableview单元格中点击不同的按钮时,我想播放不同的声音。现在,当我点击它们时,每个按钮播放相同的音频文件。当我点击不同的按钮时,如何告诉我的应用播放不同的音频文件。
这是我的代码
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()
}
}
}
答案 0 :(得分:0)
if let url = Bundle.main.url(forResource: soundArrayRifles[sender.tag], withExtension: "mp3") {
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()
}
试试这个。这应该解决它。