播放Next Song AVAudioPlayer

时间:2017-06-01 11:22:19

标签: ios swift avfoundation avaudioplayer

我有一个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

1 个答案:

答案 0 :(得分:0)

你可以在 Librarydetailviewcontroller 中传递一系列歌曲列表,并使用audioPlayerDidFinishPlaying委托进行下一首歌...否则你可以在“nextButtonTapped”上使用 playCurrentSong func

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