使用相同的按钮快速播放和停止音乐

时间:2017-05-12 04:56:20

标签: ios swift audio avaudioplayer

如何使用单个按钮进行音乐播放和停止,就像在iTunes中一样。当按下按钮并再次按下相同的按钮时,应停止播放音乐。

  var audioplayer = AVaudioPlayer
 @IBAction func play(_ sender: Any) {

    do
    {

        audioPlayer = try AVAudioPlayer (contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "bensound", ofType: "mp3")!))
        audioPlayer.prepareToPlay()
        audioPlayer.play()
        audioPlayer.stop()

    }
    catch {
        print ("error")

    }

}

1 个答案:

答案 0 :(得分:2)

显然,这不会起作用:

audioPlayer.prepareToPlay()
audioPlayer.play() // this will just start playing the music and immediately stop it.
audioPlayer.stop()

您需要一个if语句和一个表示音乐是否正在播放的变量。

幸运的是,我所谈论的变量已经存在!你甚至不需要自己申报!它是isPlaying,在AVAudioPlayer中定义。

我们只需编写if语句。这很简单,

  

如果正在播放音乐,请将其停止,否则启动它

if audioplayer.isPlaying {
    audioplayer.play()
} else {
    audioplayer.stop()
}
相关问题