Home > OS >  Trying to play music through AVPlayer in a uitableview, but the wrong music is being played (wrong m
Trying to play music through AVPlayer in a uitableview, but the wrong music is being played (wrong m

Time:09-17

So I have a UITableViewController, and inside each cell is a play button and a pause button in order to play music. When you press the play button, it should play the music specific to that cell, however when I run my code, it plays random audio, not the one I specifically loaded for it. Also when I scroll through the tableview, the audio stops playing. Why is this the case and how do I fix it? I also want it to switch songs if the play button in a different cell is pressed.

Here is the function that I use to load the unique string (produced by post.mp3) to find the url file into my AVPlayer:

func loadAudio(post: CompPost, completion: @escaping (URL) -> ())
    {
        let audioRef = Storage.storage().reference().child("cPosts").child(post.uid).child("Audio").child(post.mp3)
        audioRef.downloadURL
        { (url, error) in
            print("mp3filename: "   post.mp3)
            guard error == nil else
            {
                print(error!.localizedDescription)
                return /**alert**/
            }
            self.audioPlayer = AVPlayer(playerItem: AVPlayerItem(url: url!))
            completion(url!)
        }
    }

Here is the code that loads the unique url for each cell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cPostCell", for: indexPath) as! cPostCell
            
        cell.delegate = self
        cell.index = indexPath
        
        //other code omitted for brevity

        loadAudio(post: compPosts[indexPath.row])
        { (url) in
            print("THIS IS THE URL")
            print(url)
        }
        
        return cell
    }

function for hitting the play button:

func playMusic(index: Int)
    {
        audioPlayer.play()
        isPlaying = true
        print("playing now")
    }

CodePudding user response:

The problem is that you are not loading new AVPlayerItem into your AVPlayer when you trigger audioPlayer.play() Therefore when you hit play button, player starts to play the Item that was loaded in your last loaded tableViewCell . Try saving all playerItems into array with some index , and when user taps the button with index you load the audio and within loading you assign new AVPlayerItem into AVPlayer :

 audioPlayer = AVPlayer(playerItem: yourPlayerItemArray[index]))

and after that you trigger audioPlayer.play()

  • Related