简体   繁体   中英

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

这是截图请检查

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.

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.

Add in Your ViewController

var currentPlayingIndex: Int?

.....
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

    self.currentPlayingIndex = indexPath.row
    self.loadSongFromURL()
}
.....

//Button Action..
@IBAction func nextButtonAction(_ sender: Any){

    self.playSong(isForward: true)
}

@IBAction func previousButtonAction(_ sender: Any) {

    self.playSong(isForward: false)
}

private func playSong(isForward: Bool) {

    if currentPalyingIndex == nil { //Means not any song is playing
        currentPalyingIndex = 0
        self.loadSongFromURL()
    }
    else{

        if isForward {

            if self.currentPalyingIndex! < self.items.count-1 {
                self.currentPalyingIndex = self.currentPalyingIndex! + 1
                self.loadSongFromURL()
            }
            else {
                // handle situation while reach at last
            }
        }
        else {
            if self.currentPalyingIndex! > 0 {
                self.currentPalyingIndex = self.currentPalyingIndex! - 1
                self.loadSongFromURL()
            }
            else {
                // handle situation while reach at 0
            }
        }
    }
}

// Load Song
func loadSongFromURL(){

   let urlstring = songs[self.currentPalyingIndex]
   let strnew = urlstring.replacingOccurrences(of: "\"", with: "")
   downloadFileFromURL(url: strnew)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM