view raw
Volkan Elçi Volkan Elçi - 6 months ago 32
Swift Question

How to play different sounds in different buttons in tableview

I want to play different sounds when i tap different buttons in my tableview cells. Right now every button plays the same audio file when i tap them. How can i tell my app to play different audio files when i tap different buttons.


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() {


override func 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.insert(AVPlayerItem(url: url), after: nil)



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


Try this. This should fix it.