繁体   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