如何同步播放“幻灯片”和播放音频文件

时间:2019-04-10 07:12:16

标签: swift

我正在尝试将UICollectionView中的幻灯片播放与音频文件的播放同步。我想做的是先播放音频,等待音频播放完成,然后滚动到下一张重复该过程的幻灯片。问题是幻灯片先滚动,然后播放音频文件,即未同步。

我尝试通过实现一个计时器来实现此目的,然后使用dispatchQueue方法同步音频的播放顺序,然后同步幻灯片的滚动。但是,我无法完全同步它。我已经检查了StackOverFlow中的其他答案,包括:Waiting until the task finishes。而且我可以看到,主要问题之一是应用程序需要识别音频文件何时完成播放(不仅仅是开始时)。为了解决这个问题,我研究了功能-swift. AVPlayer. How to track when song finished playing?。但是,我不能整合这一点。我将不胜感激。

这是计时器功能:

  func startSlideTimer() {

        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.scrollAutomatically), userInfo: nil, repeats: true)
    }

scrollAutomatically是这个

@objc func scrollAutomatically() {

        if let scrollCollectionView  = collectionView {
            for cell in scrollCollectionView.visibleCells {
                let indexPath = scrollCollectionView.indexPath(for: cell)!

                print("Scroll indexPath is \(indexPath)")

                let group = DispatchGroup()
                group.enter()

                DispatchQueue.main.async {
                    self.playAVatIndex()

                    if self.audioFinished == true {
                    group.leave()
                    }  *** This does not work


                }

                group.notify(queue: .main) {
                    if (indexPath.row < (self.selectedStory?.storyItems.count)! - 1) {

                        let indexPath1: IndexPath?

                        indexPath1 = IndexPath.init(row: (indexPath.row) + 1, section: (indexPath.section))

                        scrollCollectionView.scrollToItem(at: indexPath1!, at: .right, animated: true)

                    }

                    else {
                        self.stopTimer()
                    }
                }

            }
        }
    }

在这里播放音频文件功能:

@objc func playAVatIndex() {

    if let scrollCollectionView  = collectionView {
        for cell in scrollCollectionView.visibleCells {
            let indexPath = scrollCollectionView.indexPath(for: cell)!

            let storyItem = selectedStory!.storyItems[indexPath.row]
            setUpPlayer(storyItem: storyItem)
            audioPlayer.play()

        }
    }
}

检测播放结束的功能:

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        print("Finished playing")
        audioFinished = true *** assigned to relevant global variable
    }

在此先感谢您的帮助。

0 个答案:

没有答案