2015-02-23 138 views
0

我正在嘗試構建一個按鈕,可以在我的iOS遊戲中啓動/停止背景音樂。我可以玩它,但是當我再次點擊它時,它只是重新開始而不是停止。這是我使用的代碼。使用AVAudioPlayer啓動/停止背景音樂按鈕

我在做什麼錯?

func playBackgroundMusic(filename: String) { 
    let url = NSBundle.mainBundle().URLForResource(
     filename, withExtension: nil) 
    if url == nil { 
     println("Could not find file: \(filename)") 
     return 
    } 
    var error: NSError? = nil 
    backgroundMusicPlayer = 
     AVAudioPlayer(contentsOfURL: url, error: &error) 
    if backgroundMusicPlayer == nil { 
     println("Could not create audio player: \(error!)") 
     return 
    } 
    if backgroundMusicPlayer.playing { 
     backgroundMusicPlayer.stop() 
     backgroundMusicPlayer.currentTime = 0 
    } else { 
     backgroundMusicPlayer.numberOfLoops = -1 
     backgroundMusicPlayer.prepareToPlay() 
     backgroundMusicPlayer.play() 
    } 
} 
+0

也許用'pause',而不是'stop'?或者,獲取'currentTime',然後將其傳遞給'playAtTime:' – 2015-02-23 15:54:08

回答

1

playBackgroundMusic方法很混亂。您創建新的AVAudioPlayer並將其分配給backgroundMusicPlayer。當然,新實例並不在播放,因此每次調用此函數時都會開始播放。

您應該創建新AVAudioPlayer如果當前是nil

func playBackgroundMusic(filename: String) { 
    if backgroundMusicPlayer == nil { 
     let url = NSBundle.mainBundle().URLForResource(
      filename, withExtension: nil) 
     if (url == nil) { 
      println("Could not find file: \(filename)") 
      return 
     } 
      var error: NSError? = nil 
     backgroundMusicPlayer = 
      AVAudioPlayer(contentsOfURL: url, error: &error) 
     if backgroundMusicPlayer == nil { 
      println("Could not create audio player: \(error!)") 
      return 
     } 
    } 

    if(backgroundMusicPlayer.playing == true) 
    { 
     backgroundMusicPlayer.stop() 
     backgroundMusicPlayer.currentTime = 0 
    } 
    else 
    { 
     backgroundMusicPlayer.numberOfLoops = -1 
     backgroundMusicPlayer.prepareToPlay() 
     backgroundMusicPlayer.play() 
    } 
} 
+0

非常感謝! – 2015-02-23 16:39:44