簡體   English   中英

如何在下一個按鈕單擊時播放下一首歌曲

[英]how to play next song on next button click

我正在使用AVAudioPlayer()創建音樂播放器,所以我有多個JSON格式的音頻文件 url,所以我在 tableview 中顯示所有內容,然后在didSelect上我正在播放選定的歌曲,但我想在按鈕上播放下一首歌曲點擊這里是我的代碼在didSelect上播放歌曲

didSelect 代碼

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

這是我從 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()
        }
    }
}

使用下面的代碼,我正在播放音頻

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")
    }
}

但我無法理解如何在單擊下一個按鈕時播放下一首歌曲我在下面分享我的User Interface的屏幕截圖

這是截圖請檢查

didSelect上,我可以播放所選歌曲,但如何管理下一首我不確定,請幫幫我。

在 ViewController 中只需維護一個索引值。

喜歡:

var currentIndex = 0

在 didSelect 方法中用 indexPath 行值更新當前索引值

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

使用另一種方法獲取 URL 並播放歌曲。 將會

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

對於上一個/下一個按鈕操作將是

@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()
     }
}

希望你能理解。

添加你的 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM