使用AVAudioPlayer启动/停止背景音乐按钮

时间:2015-02-23 15:47:40

标签: ios swift

我正在尝试构建一个单独的按钮,用于在我的iOS游戏中启动/停止背景音乐。我可以让它玩,但当我再次点击它时,它只是重新启动而不是停止。这是我使用的代码。

我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

playBackgroundMusic方法非常混乱。您创建新的AVAudioPlayer并将其分配给backgroundMusicPlayer。当然新的实例没有播放,因此每次调用此函数时它都会开始播放。

如果当前的AVAudioPlayernil,则应创建新的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() } }

{{1}}