gpt4 book ai didi

ios - 快速播放和停止音乐

转载 作者:行者123 更新时间:2023-12-03 02:36:38 26 4
gpt4 key购买 nike

就像在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")

}

}

最佳答案

显然,这是行不通的:

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

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

幸运的是,我正在谈论的变量已经存在!您甚至不需要自己声明它!它是 isPlaying ,在 AVAudioPlayer中定义。

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

If the music is playing, stop it, otherwise, start it


if audioplayer.isPlaying {
audioplayer.play()
} else {
audioplayer.stop()
}

关于ios - 快速播放和停止音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com