创建要播放的音乐文件队列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建要播放的音乐文件队列相关的知识,希望对你有一定的参考价值。
我有10个音乐文件的URL。我想创建所有歌曲逐个播放的音乐队列,我也可以更改特定文件的索引。
我正在使用swift 2.0
例如:iPhone的默认播放列表播放。
答案
您可以使用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了解更多信息。
希望它会有所帮助。
以上是关于创建要播放的音乐文件队列的主要内容,如果未能解决你的问题,请参考以下文章