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()
}
}
也許用'pause',而不是'stop'?或者,獲取'currentTime',然後將其傳遞給'playAtTime:' – 2015-02-23 15:54:08