我有10个音乐文件的网址。我想创建所有歌曲逐个播放的音乐队列,我也可以更改特定文件的索引。
我正在使用swift 2.0
对于前者: iPhone的默认播放列表播放。
答案 0 :(得分:2)
您可以使用AVAudioPlayerDelegate
,如下面的示例代码所示:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var counter = 0
var song = ["1","2","3"] //Song names array
var player = AVAudioPlayer()
@IBOutlet weak var musicSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
musicSlider.value = 0.0
}
func updateMusicSlider(){
musicSlider.value = Float(player.currentTime)
}
@IBAction func playSong(sender: AnyObject) {
music()
}
@IBAction func sliderAction(sender: AnyObject) {
player.stop()
player.currentTime = NSTimeInterval(musicSlider.value)
player.play()
}
func music(){
let audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "mp3")!
var error : NSError? = nil
do {
player = try AVAudioPlayer(contentsOfURL: NSURL(string: audioPath)!)
} catch let error1 as NSError {
error = error1
}
musicSlider.maximumValue = Float(player.duration)
NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("updateMusicSlider"), userInfo: nil, repeats: true)
player.delegate = self
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
}
// Delegate method for AVAudioPlayerDelegate which is called every time when song finished.
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool){
if flag {
counter++
}
if ((counter + 1) == song.count) {
counter = 0
}
music()
}
}
Sample了解更多信息。
希望它会有所帮助。