Swift - 如何通过AVAudioPlayer()播放数组中的歌曲列表

时间:2017-11-08 16:50:31

标签: swift xcode

我正在尝试创建一个简单的音乐播放器应用程序,其中包含我可以按播放按钮播放我的歌曲列表数组的歌曲,我无法弄清楚如何设置播放按钮以有序地播放歌曲数组。这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @IBOutlet weak var musicName: UILabel!

    var player = AVAudioPlayer()
    var songs = ["Rain", "Daze", "Temple of Thought"]


    override func viewDidLoad() {
        super.viewDidLoad()        
    }


    func playingMusic() {


        let path = Bundle.main.path(forResource: songs[0], ofType: "mp3")
        let url  = NSURL(fileURLWithPath: path!)

        player   = try! AVAudioPlayer(contentsOf: url as URL)
        player.prepareToPlay()
        player.numberOfLoops = 1
        player.play()

    }

    @IBAction func play(_ sender: Any) {
        playingMusic() // This just play one song in my Songs List. How to set this function to play orderly song in my Songs List ?

    }
    @IBAction func Stop(_ sender: Any) {
        player.stop()
    }
}

1 个答案:

答案 0 :(得分:1)

您可以查看AVQueuePlayer,因为文档说您可以使用它来按顺序播放多个项目。