音频播放按钮 - 开始、停止
Audio play button - Start, Stop
我是 swift 的新手,在此先感谢您的帮助。我正在设计音频播放按钮。下面是代码。该按钮将显示“开始”和“停止”。单击“开始”后,音频播放过程中按钮显示“停止”,没错。问题在于,在完成整个音频文件播放后,以下代码无法自动将按钮显示从“停止”翻转回“开始”。在按两次返回“开始”之前,它卡在“停止”。
@IBAction func didTapButton() {
if let player = player, player.isPlaying {
// Stop playback
button.setTitle("start", for: .normal)
player.stop()
}
else {
// set up player, and play
button.setTitle("stop", for: .normal)
let urlString = Bundle.main.path(forResource: "go", ofType: "mp3")
do {
try AVAudioSession.sharedInstance().setMode(.default)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
guard let urlString = urlString else {
return
}
player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlString))
guard let player = player else {
return
}
player.play()
}
catch {
print("something went wrong")
}
}
}
您需要实施AVAudioPlayerDelegate
并为玩家设置委托
player.delegate = self
然后更新按钮标题:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
button.setTitle("start", for: .normal)
}
我是 swift 的新手,在此先感谢您的帮助。我正在设计音频播放按钮。下面是代码。该按钮将显示“开始”和“停止”。单击“开始”后,音频播放过程中按钮显示“停止”,没错。问题在于,在完成整个音频文件播放后,以下代码无法自动将按钮显示从“停止”翻转回“开始”。在按两次返回“开始”之前,它卡在“停止”。
@IBAction func didTapButton() {
if let player = player, player.isPlaying {
// Stop playback
button.setTitle("start", for: .normal)
player.stop()
}
else {
// set up player, and play
button.setTitle("stop", for: .normal)
let urlString = Bundle.main.path(forResource: "go", ofType: "mp3")
do {
try AVAudioSession.sharedInstance().setMode(.default)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
guard let urlString = urlString else {
return
}
player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlString))
guard let player = player else {
return
}
player.play()
}
catch {
print("something went wrong")
}
}
}
您需要实施AVAudioPlayerDelegate
并为玩家设置委托
player.delegate = self
然后更新按钮标题:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
button.setTitle("start", for: .normal)
}