简体   繁体   English

如何在下一个按钮单击时播放下一首歌曲

[英]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我正在使用AVAudioPlayer()创建音乐播放器,所以我有多个JSON格式的音频文件 url,所以我在 tableview 中显示所有内容,然后在didSelect上我正在播放选定的歌曲,但我想在按钮上播放下一首歌曲点击这里是我的代码在didSelect上播放歌曲

didSelect Code didSelect 代码

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这是我从 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但我无法理解如何在单击下一个按钮时播放下一首歌曲我在下面分享我的User Interface的屏幕截图

这是截图请检查

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.didSelect上,我可以播放所选歌曲,但如何管理下一首我不确定,请帮帮我。

In ViewController just maintain an index value.在 ViewController 中只需维护一个索引值。

Like:喜欢:

var currentIndex = 0

In didSelect method update the current index value with the indexPath row value在 didSelect 方法中用 indexPath 行值更新当前索引值

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

Use another method to get the URL and play the song.使用另一种方法获取 URL 并播放歌曲。 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添加你的 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.

相关问题 如何在mpmoviePlayer中播放下一首歌? - how to play next song in mpmoviePlayer? 播放下一首歌曲AVAudioPlayer - Play Next Song AVAudioPlayer 如何使用线程通过MPRemoteCommandCenter播放下一首歌曲? - How to use thread to play next song by MPRemoteCommandCenter? 当第一首歌结束后,如何在表视图中自动播放下一首歌 - How to play the next song in tableview automatically when first song finish 如何在单击按钮时播放下一个声音片段? - how to play next sound clip on single button click action? 如何在remoteControlledEvents中选择下一首歌曲 - How to choose next song in remoteControlledEvents 如何在使用AVPlayer播放时开始播放下一首歌曲或确认歌曲已完成? - How to start next a Song or recognized that a song is finished while playing with AVPlayer? 在iOS音乐中播放完音乐后播放音乐时播放下一首歌 - play next song when music when music is finished in iOS swift MediaItemCollection中的下一首歌曲? - Next Song in MediaItemCollection? 在歌曲加载时间中,如果用户使用AVAudioplayer单击iPhone中的播放按钮,如何显示活动指示器 - In song loading time how to display activity indicator if user click the play button in iPhone using AVAudioplayer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM