所以我一直在尝试在播放音频时更新进度条。因此,当您点击播放按钮时,音频开始播放,进度条应该开始更新,但事实并非如此!没有任何事情发生,进展保持在0。
class HomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, HomeCollectionCellDelegate {
func didPlayButtonPressed(cell: HomeCollectionViewCell) {
if let indexPath = collectionView.indexPathForCell(cell) {
if isPlayingAudio == false {
audioPlayer = AVPlayer(URL: NSURL(string: posts[indexPath.row].audioFile.url!)!)
self.audioPlayer.play()
isPlayingAudio = true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.doTimeConsumingWork(cell)
}
}
}
var percentage: Float = 0
var currentCounter: Float = 0
func doTimeConsumingWork(cell: HomeCollectionViewCell) {
if let indexPath = collectionView.indexPathForCell(cell) {
var duration = Float(CMTimeGetSeconds((audioPlayer.currentItem?.duration)!))
var currentTime = Float(CMTimeGetSeconds((audioPlayer.currentItem?.currentTime())!))
while currentCounter < duration {
var x = currentTime / duration
currentCounter += x
percentage = Float(currentCounter) / Float(duration)
dispatch_async(dispatch_get_main_queue()) {
// self.updateProgressBar(cell)
self.setProgressAtIndex(indexPath.row, withProgress: self.percentage/100.0)
}
//Finished doing time consuming work
cell.progressBar.setProgress(0.0, animated: true)}
}
}
func setProgressAtIndex(index: NSInteger, withProgress progress: Float) {
if let cell: HomeCollectionViewCell = self.collectionView.cellForItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as! HomeCollectionViewCell {
cell.progressBar.setProgress(progress, animated: true)
}
}
}