如何持续检查 AVAudioplayer 是不是已在 Swift 中播放完毕?
Posted
技术标签:
【中文标题】如何持续检查 AVAudioplayer 是不是已在 Swift 中播放完毕?【英文标题】:How do I continuously check if AVAudioplayer is done playing in Swift?如何持续检查 AVAudioplayer 是否已在 Swift 中播放完毕? 【发布时间】:2015-09-28 22:15:30 【问题描述】:我制作了一个播放音频的简单应用。现在我想在音频播放完毕后自动将“暂停”按钮更改为“播放”。我该如何检查? 代码如下:
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 语句应该在函数内部,但是我如何(连续)调用该函数?
【问题讨论】:
【参考方案1】:您不必不断检查 - 您应该在视图控制器中实现 AVAudioPlayerDelegate 协议:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerDelegateProtocolReference/index.html#//apple_ref/occ/intfm/AVAudioPlayerDelegate/audioPlayerDidFinishPlaying:successfully:
请参阅:audioPlayerDidFinishPlaying:successfully:
。我想你会发现它与你想做的完全相反,这实际上是正确的方法。这样,您的播放器将简单地调用您定义的“结束”函数。
【讨论】:
【参考方案2】:这么多重复的问题...这是我重复的答案:
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
【讨论】:
以上是关于如何持续检查 AVAudioplayer 是不是已在 Swift 中播放完毕?的主要内容,如果未能解决你的问题,请参考以下文章
AVAudioPlayer 持续时间与音频文件的实际持续时间不匹配
AVAudioPlayer currentTime 超过持续时间
使用 MPRemoteCommandCenter 为 AVPlayer 和 AVAudioPlayer 添加当前时间和持续时间的位置