Ios 播放下一首歌曲AVAudioPlayer

Ios 播放下一首歌曲AVAudioPlayer,ios,swift,avfoundation,avaudioplayer,Ios,Swift,Avfoundation,Avaudioplayer,我有一个tableviewcontroller,它有一个歌曲列表,每当用户单击一首歌曲时,它就会打开另一个视图控制器并播放它。我需要帮助,每当用户按下“下一步”按钮或“上一步”按钮,以便播放上一首或下一首歌曲。这是我的tableviewcontroller: import UIKit class LibraryTableViewController: UITableViewController { var titleText = ["Heroes", "Skyline", "In T

我有一个tableviewcontroller,它有一个歌曲列表,每当用户单击一首歌曲时,它就会打开另一个视图控制器并播放它。我需要帮助,每当用户按下“下一步”按钮或“上一步”按钮,以便播放上一首或下一首歌曲。这是我的tableviewcontroller:

import UIKit

class LibraryTableViewController: UITableViewController {

    var titleText = ["Heroes", "Skyline", "In The Woods"]
    var authorText = ["Kedam", "Kovan & Electro Light", "Max Pros"]

    @IBOutlet var songList: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()



    }


    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return titleText.count
    }

    //tableview delegate

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell
        if(cell == nil)
        {
            cell = Bundle.main.loadNibNamed("Library Cell", owner: self, options: nil)?[0] as! LibrarySongTableViewCell;
        }
        let titleTitle = titleText[indexPath.row] as String //NOT NSString
        let authorTitle = authorText[indexPath.row] as String
        cell.titleLabel.text=titleTitle
        cell.authorLabel.text=authorTitle
        cell.imageView?.image = UIImage(named: titleTitle)
        cell.imageView?.layer.cornerRadius = 5
        return cell as LibrarySongTableViewCell

    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == "toLibraryDetail"
        {
            let detailViewController = ((segue.destination) as! LibraryDetailViewController)
            let indexPath = self.songList!.indexPathForSelectedRow!
            let topicLabelText = titleText[indexPath.row]
            let detailLabelText = authorText[indexPath.row]
            detailViewController.titleLabelText = topicLabelText
            detailViewController.authorLabelText = detailLabelText



        }

    }

}
以下是单元格播放歌曲时所使用的视图控制器:

    import UIKit
    import AVFoundation
    import MediaPlayer

    // audioPlayer Outlet
    var libraryPlayer = AVAudioPlayer()

    class LibraryDetailViewController: UITableViewController, AVAudioPlayerDelegate {

        // Title and Author
        var titleLabelText: String!
        var authorLabelText: String!
        @IBOutlet weak var albumArt: UIImageView!
        @IBOutlet weak var titleText: UILabel!
        // Image Outlets
        @IBOutlet weak var authorText: UILabel!
        @IBOutlet weak var blurredAlbumArt: UIImageView!
        // Toolbar Outlets
        @IBOutlet weak var toolbar: UIToolbar!
        var playButton: UIBarButtonItem!
        var pauseButton: UIBarButtonItem!
        var flexibleSpace: UIBarButtonItem!
        var nextButton: UIBarButtonItem!
        var previousButton: UIBarButtonItem!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Customize Album Art
            albumArt.image = UIImage(named: titleLabelText)
            blurredAlbumArt.image = UIImage(named: titleLabelText)
            albumArt.layer.cornerRadius = 10
            // Set label text
            titleText.text = titleLabelText
            authorText.text = authorLabelText


            // Create the audioPlayer
            do {

                libraryPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: titleLabelText, ofType: "mp3")!))
                libraryPlayer.delegate = self


                libraryPlayer.prepareToPlay()

                var audioSession = AVAudioSession.sharedInstance()



                do {

                    try audioSession.setCategory(AVAudioSessionCategoryPlayback)

                }

            }

            catch {

                print(error)

            }

            //  Create ToolBar Buttons
            playButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.play, target: self, action: "playButtonTapped")
            pauseButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.pause, target: self, action: "pauseButtonTapped")
            flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
            previousButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.rewind, target: self, action: "previousButtonTapped")
            nextButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fastForward, target: self, action: "nextButtonTapped")

            //  Customize ToolBar Buttons
            previousButton.tintColor = UIColor.lightGray
            nextButton.tintColor = UIColor.lightGray

            toolbar.items = [flexibleSpace, previousButton, flexibleSpace, pauseButton, flexibleSpace, nextButton, flexibleSpace]


            // Set the delegate

            // Play
            libraryPlayer.play()



            // Do any additional setup after loading the view.
        }

        //  Play
        func playButtonTapped() {
            toolbar.items = [flexibleSpace, previousButton, flexibleSpace, pauseButton, flexibleSpace, nextButton, flexibleSpace];
            libraryPlayer.play()
        }

        //  Pause
        func pauseButtonTapped() {
            toolbar.items = [flexibleSpace, previousButton, flexibleSpace, playButton, flexibleSpace, nextButton, flexibleSpace];
            libraryPlayer.pause()
        }

        //  Previous
        func previousButtonTapped() {
// NEED HELP HERE
        }

        //  Next
        func nextButtonTapped() {
// NEED HELP HERE
        }

        override func viewDidDisappear(_ animated: Bool) {
            libraryPlayer.pause()
        }

        override func viewDidAppear(_ animated: Bool) {
            libraryPlayer.play()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


        @IBAction func dismiss(_ sender: Any) {
            dismiss(animated: true, completion: nil)
        }
    }

非常感谢你的帮助!我正在使用Swift 3和Xcode 8

您可以在Librarydetailviewcontroller中传递歌曲列表数组,并使用AudioPlayerDifinishPlaying代理播放下一首歌曲…否则您可以在“下一个按钮”上使用播放当前歌曲函数


请看这篇文章@VarinderSingh我还没有诱惑目标C。你有Swift的东西吗?谢谢
var currentSoundsIndex: Int = 0

override func viewDidLoad() {
super.viewDidLoad()
currentSoundsIndex = 0
playCurrentSong()
}

func playCurrentSong() {
var error: Error?
mediaPlayer = try? AVAudioPlayer(contentsOfURL: URL(fileURLWithPath: Bundle.main.path(forResource: soundList[currentSoundsIndex], ofType: nil)))
if error != nil {
    print("\(error)")
    //Also possibly increment sound index and move on to next song
}
else {
    lblCurrentSongName.text = soundList[currentSoundsIndex]
    mediaPlayer.delegate = self
    mediaPlayer.prepareToPlay()
    //This is not always needed, but good to include
    mediaPlayer.play()
    }
}


func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
//Increment index but don't go out of bounds
currentSoundsIndex = currentSoundsIndex += 1 % soundList.count
playCurrentSong()
}