Ios 如何持续检查AVAudioplayer是否在Swift中播放?
我制作了一个播放音频的简单应用程序。现在我想在音频播放完毕后自动将“暂停”按钮更改为“播放”。我怎么检查这个? 代码如下:Ios 如何持续检查AVAudioplayer是否在Swift中播放?,ios,swift,audio,Ios,Swift,Audio,我制作了一个播放音频的简单应用程序。现在我想在音频播放完毕后自动将“暂停”按钮更改为“播放”。我怎么检查这个? 代码如下: import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var PausePlay: UIButton! var BackgroundAudio = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:
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语句应该在函数中,但是我如何(连续地)调用该函数呢?您不必不断地检查-您应该在视图控制器中实现AVAudioPlayerDelegate协议::
请参阅:
audioPlayerDidFinishPlaying:successfully:
。我想你会发现它与你想做的恰恰相反,这实际上是正确的方法。这样,您的播放器只需调用您定义的“end”函数。这么多重复的问题……下面是我重复的答案:
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController,AVAudioPlayerDelegate {
var player: AVAudioPlayer = AVAudioPlayer()
@IBAction func play(_ sender: UIButton) {
player.play()
player.currentTime=14*60-10
print(player.currentTime)
}
@IBAction func pause(_ sender: UIButton) {
player.pause()
}
@IBAction func replay(_ sender: UIButton) {
player.currentTime=0
}
override func viewDidLoad() {
super.viewDidLoad()
do{
let audioPath = Bundle.main.path(forResource: "elon", ofType: "mp3")
player = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: audioPath!))
player.prepareToPlay()
player.delegate = self
}
catch{
print(error)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){
print(flag)
print("here")
if flag == true{
}
}
}