gpt4 book ai didi

ios - 如何连续检查 AVAudioplayer 是否已在 Swift 中播放完毕?

转载 作者:可可西里 更新时间:2023-11-01 00:23:34 25 4
gpt4 key购买 nike

我制作了一个简单的播放音频的应用程序。现在我想在音频播放完毕后自动将“暂停”按钮更改为“播放”。我该如何检查?这是代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {
@IBOutlet weak var PausePlay: UIButton!
var BackgroundAudio = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("M.I.A.-DoubleBubbleTrouble", ofType: "mp3")!), error: nil)

override func viewDidLoad() {
super.viewDidLoad()
BackgroundAudio.play()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func Stop(sender: AnyObject) {
if(BackgroundAudio.playing) {
BackgroundAudio.stop()
BackgroundAudio.currentTime = 0
PausePlay.setTitle("Play", forState: .Normal)
} else {
BackgroundAudio.currentTime = 0
}
}

@IBAction func Restart(sender: AnyObject) {
if(BackgroundAudio.playing==false){
PausePlay.setTitle("Pause", forState: .Normal)
}
BackgroundAudio.stop()
BackgroundAudio.currentTime = 0
BackgroundAudio.play()
}

@IBAction func PausePlay(sender: AnyObject) {
if(BackgroundAudio.playing){
BackgroundAudio.stop()
PausePlay.setTitle("Play", forState: UIControlState.Normal)
} else {
BackgroundAudio.play()
PausePlay.setTitle("Pause", forState: .Normal)
}
}

if (BackgroundAudio.playing == false) {
PausePlay.setTitle("Play", forState: .Normal)
}
}

最后一个 if 语句应该在函数内部,但是我该如何(连续)调用该函数?

最佳答案

您不必不断检查 - 您应该改为在 View Controller 中实现 AVAudioPlayerDelegate 协议(protocol):https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/index.html#//apple_ref/occ/intfm/AVAudioPlayerDelegate/audioPlayerDidFinishPlaying:successfully :

参见:audioPlayerDidFinishPlaying:成功:。我想你会发现它做的和你想做的完全相反,这实际上是正确的方法。这样,您的播放器将简单地调用您定义的“结束”函数。

关于ios - 如何连续检查 AVAudioplayer 是否已在 Swift 中播放完毕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832679/

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