展开segue和音频继续播放

展开segue和音频继续播放

问题描述:

我有一个显示全屏单元格的集合视图。当细胞自动滚动一个接一个。当滚动发生时,音频文件播放取决于单元格的索引号。这部分没有问题。但我的问题是,我有一个后退按钮,当用户点击它时,用户转到主视图控制器。这个后退按钮有一个放松的过程。当我点击后退按钮时,我转到主视图控制器,但收集视图单元格滚动时播放的音频文件不停地播放。展开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() 
     } 

我觉得unwind()功能不释放你的viewController实例。您无法再技术性地访问viewController实例,但它的内存实例仍保留在内存中,并让您的AudioPlayer继续播放。尝试使用

self.dismiss(animated: true, completion: { 
    [unowned self]() -> Swift.Void in 
    self.yourPlayer.stop(); 
    self.yourPlayer = nil; 
}) 

或停止和释放你的unwind()赛格瑞函数内部audioPlayers。

使用在prepareForSegue方法这些线路

if audioPlayer1.isPlaying == true { 
    audioPlayer1.stop() 

而且还可以确保你正在呼吁当前播放的音频播放器的同一实例stop()方法。