首页 > 解决方案 > 无法从阵列中获取要播放的正确音频文件

问题描述

当我点击表格视图中的任何单元格时,它们都会在第一个数组中播放相同的歌曲。如何让他们播放分配给他们个人阵列的歌曲?func automaticPlay() 负责处理这个vc上的音频。点击单元格时,歌曲应自动播放。

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import AVFoundation

class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet var tableViewProducts: UITableView!
    var delegate: ListViewController?

    var ref:DatabaseReference?
    var databaseHandle: DatabaseHandle?
    let audioStuffed = false
    let audioPlayer = AVPlayer()
    var postData = [productsList]()
    var player: AVPlayer!


    func automaticPlay() {
        let indexPath = IndexPath(row: 0, section: 0)
        let audioUp = postData[indexPath.row].audio
        let url = audioUp

        player = AVPlayer(url: URL(string: url!)!)

        player.volume = 1.0
        player.rate = 1.0
        if player.rate == 0 {
            player.play()
            print("It's Playing")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        ref = Database.database().reference().child("AudioDB")
        loadProducts()

        do {
            try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        }
    }

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

    func loadProducts() {
        ref?.observe(DataEventType.value, with: { (snapshot) in
            var newSweets = [productsList]()

            for post in snapshot.children {
                let postObject = productsList(snapshot: post as! DataSnapshot)
                newSweets.append(postObject)
                print(self.postData)

            }
            self.postData = newSweets
            self.tableViewProducts.reloadData()
        }) { (error:Error) in
            print(error)
        }
    }

    //This places the text on the ViewControllerTableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

        let sweet = postData[indexPath.row]

        cell.idLbl.text = sweet.id
        cell.nameLbl.text = sweet.p_name

        if let profileImageUrl = sweet.image{
            let url = URL(string: profileImageUrl)
            URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                if error != nil {
                    print(error)
                    return
                }
                DispatchQueue.main.async {
                    cell.productImage.image = UIImage(data: data!)
                }
            }).resume()
        }
        return cell
    }

    var selectedRowIndex = -1

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == selectedRowIndex {
            automaticPlay()
            return 200 //Expanded
        }
        return 40//Not expanded
}
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectedRowIndex == indexPath.row {
            selectedRowIndex = -1

        } else {
            selectedRowIndex = indexPath.row
        }
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }
}

标签: iosarraysswiftuitableviewaudio

解决方案


评论者是正确的。您从错误的地方调用自动播放。从 didSelectRowAt 中调用它,并删除自动播放中定义 indexPath 的行。而是使用在 didSelectRowAt 中传递的 indexPath。


推荐阅读