我有一個顯示全屏單元格的集合視圖。當細胞自動滾動一個接一個。當滾動發生時,音頻文件播放取決於單元格的索引號。這部分沒有問題。但我的問題是,我有一個後退按鈕,當用戶點擊它時,用戶轉到主視圖控制器。這個後退按鈕有一個放鬆的過程。當我點擊後退按鈕時,我轉到主視圖控制器,但收集視圖單元格滾動時播放的音頻文件不停地播放。展開segue和音頻繼續播放
我都試過,但它不工作
@IBAction func backBtnPressed(_ sender: UIButton) {
if audioPlayer1.isPlaying == true {
audioPlayer1.stop()
}
,我打電話裏面的一切viewDidLoad()
override func viewDidLoad() {
startTimer()
}
這是部分自動處理滾動到下一個單元格。我在這裏打電話alphabetSoundPlay()
功能。
func scrollToNextCell(){
let cellSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
let contentOffset = myCollectionView.contentOffset
myCollectionView.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
alphabetSoundPlay()
}
3秒延遲滾動
func startTimer() {
_ = Timer.scheduledTimer(timeInterval: 3.0,
target: self,
selector: #selector(scrollToNextCell),
userInfo: nil,
repeats: true)
}
這是函數計算出它是細胞和音頻文件將發揮
func alphabetSoundPlay() {
let currentRow = self.myCollectionView.indexPath(for: self.myCollectionView.visibleCells[0])?.row
if currentRow == 0 {
do
{
audioPlayer1 = try AVAudioPlayer(contentsOf:alphabetSound1!, fileTypeHint:nil)
}
catch
{
return print("file not found")
}
audioPlayer1.prepareToPlay()
audioPlayer1.play()
} else if currentRow == 1 {
do
{
audioPlayer2 = try AVAudioPlayer(contentsOf:alphabetSound2!, fileTypeHint:nil)
}
catch
{
return print("file not found")
}
audioPlayer2.prepareToPlay()
audioPlayer2.play()
}else if currentRow == 2 {
do
{
audioPlayer3 = try AVAudioPlayer(contentsOf:alphabetSound3!, fileTypeHint:nil)
}
catch
{
return print("file not found")
}
audioPlayer3.prepareToPlay()
audioPlayer3.play()
}else if currentRow == 3 {
do
{
audioPlayer4 = try AVAudioPlayer(contentsOf:alphabetSound4!, fileTypeHint:nil)
}
catch
{
return print("file not found")
}
audioPlayer4.prepareToPlay()
audioPlayer4.play()
}