2015-06-25 59 views
0

我試圖製作一個應用程序,播放與數組內容相關的一系列鈴聲,每當所有鈴聲播放時,應用程序都應該從數組開始再次播放它們。如何讓我的iOS應用程序不斷循環播放聲音的播放列表?

這是我的代碼:

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 
     } 

    } 
} 

我怎樣才能做到這一點?

回答

1

這裏你不需要循環。邏輯如下:您播放音樂文件,在這個文件是在你增加計數器並播放下一個文件

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

它不工作,它給了我索引超出範圍 – justel

+0

嘗試settting玩家的委託在我編輯的答案中爲零 –