как играть следующую песню при следующем нажатии кнопки - PullRequest
0 голосов
/ 03 октября 2019

я создаю музыкальный проигрыватель, используя AVAudioPlayer(), поэтому у меня есть несколько URL-адресов аудиофайлов в формате JSON, поэтому я отображаю все в виде таблицы и затем на didSelect я играю выбранную песню, но я хочу воспроизвести следующую песню нанажмите здесь, вот мой код для воспроизведения песни на didSelect

didSelect Code

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 ниже

Here is the screenshot please check

on didSelect Я могу воспроизвести выбранную песню, но как управлять следующей предыдущей, я не уверен, пожалуйста, помогите мне с этим.

Ответы [ 2 ]

0 голосов
/ 03 октября 2019

Добавить в свой 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)
}
0 голосов
/ 03 октября 2019

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

Надеюсь, вы понимаете.

...