Search code examples
iosswiftavaudioplayeravaudiosession

how to play next song on next button click


i am creating music player using AVAudioPlayer() so i have multiple Audio file urls in JSON format so i have display all in tableview and then on didSelect i am playing selected song but i want to play next song on button click here is my code for playing song on didSelect

didSelect Code

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let urlstring = songs[indexPath.row]
        let strnew = urlstring.replacingOccurrences(of: "\"", with: "")
        downloadFileFromURL(url: strnew)
}

Here is my func for Download Audio from URL

func downloadFileFromURL(url: String)  {

    if let audioUrl = URL(string: url) {

        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
        print(destinationUrl)

        if FileManager.default.fileExists(atPath: destinationUrl.path) {
            print("The file already exists at path")
            self.play(url: destinationUrl)
        } else {
            URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
                guard let location = location, error == nil else { return }
                do {
                    try FileManager.default.moveItem(at: location, to: destinationUrl)

                    self.play(url: destinationUrl)
                    print("File moved to documents folder")
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }).resume()
        }
    }
}

With below code i am playing audio

func play(url: URL) {

    print("playing \(url)")

    do {

        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0
        audioPlayer.play()

    } catch let error as NSError {

        print("playing error: \(error.localizedDescription)")

    } catch {

        print("AVAudioPlayer init failed")
    }
}

but I'm not able to understand how to play next song on next button click I am sharing a screenshot of my User Interface below

Here is the screenshot please check

on didSelect I am able to play the selected song but how to manage next previous I am not sure please help me with this.


Solution

  • In ViewController just maintain an index value.

    Like:

    var currentIndex = 0
    

    In didSelect method update the current index value with the indexPath row value

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       currentIndex = indexPath.row
       loadUrl()
    }
    

    Use another method to get the URL and play the song. Will be

    func loadUrl(){
        let urlstring = songs[currentIndex]
        let strnew = urlstring.replacingOccurrences(of: "\"", with: "")
        downloadFileFromURL(url: strnew)
    }
    

    And for previous/next button action will be

    @IBAction func nextBtnAction(_ sender: UIButton){
        if currentIndex + 1 < songs.count {
              currentIndex = currentIndex + 1
              loadUrl()
         }
    }
    
    @IBAction func previousBtnAction(_ sender: UIButton){
        if currentIndex != 0 {
              currentIndex = currentIndex - 1
              loadUrl()
         }
    }
    

    Hope you understand.