I'm trying to make an app that plays a series of chimes related to the content of an array, whenever all the chimes are played the app should start playing them again from the beginning of the array.
This is my code:
var counter = 0
var song = ["1","2","3","4"]
func music() {
while counter < song.count {
var audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "wav")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
if flag {
counter++
}
}
if ((counter + 1) == song.count) {
counter = 0
}
}
}
How can I achieve this?
You don't need to have a loop here. The logic is the following: you play a music file, when this file is over you increment the counter and play the next file
var counter = 0
var song = ["1","2","3","4"]
func music()
{
var audioPath = NSBundle.mainBundle().pathForResource("\(song[counter])", ofType: "wav")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
if error == nil {
player.delegate = self
player.prepareToPlay()
player.play()
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool)
{
player.delegate = nil
if flag {
counter++
}
if ((counter + 1) == song.count) {
counter = 0
}
music()
}