SpeechUtterance没有停止

时间:2017-08-17 14:04:33

标签: ios swift avspeechutterance

我有一个启用了分页的集合视图。我正在使用AVSpeechSynthesizer在集合视图的单元格中进行文本到语音。当我从一个牢房滑到另一个牢房时,我希望语音停止。现在我调用stopSpeech函数,它在单元类中声明。

//Cell Class
import UIKit
import AVFoundation

class DetailArticleCell: UICollectionViewCell, AVSpeechSynthesizerDelegate {
    @IBOutlet weak var articleImage: UIImageView!
    @IBOutlet weak var articleText: UILabel!
    @IBOutlet weak var textToSpeechBGView: UIVisualEffectView!
    @IBOutlet weak var textToSpeechButton: UIButton!
    var isSpeaking: Bool = true
    let speechSynthesizer = AVSpeechSynthesizer()
    var speechText: String!

    override func awakeFromNib() {
        textToSpeechBGView.layer.cornerRadius = 0.5 * textToSpeechBGView.bounds.size.width
        textToSpeechBGView.clipsToBounds = true
        setImageForTextSpeech()
        speechSynthesizer.delegate = self

    }

    func setImageForTextSpeech(){
        isSpeaking ? textToSpeechButton.setImage(#imageLiteral(resourceName: "noAudio"), for: .normal) : textToSpeechButton.setImage(#imageLiteral(resourceName: "audio"), for: .normal)
    }

    func receive(text: String) -> String{
        return text
    }
    func speak(text: String){
        let speechUtterance = AVSpeechUtterance(string: text)
       // speechUtterance.rate = 1.0
        speechSynthesizer.speak(speechUtterance)
        isSpeaking = false
    }
    func stopSpeech(){
      speechSynthesizer.stopSpeaking(at: .immediate)
      isSpeaking = true
    }

    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        isSpeaking = true
        setImageForTextSpeech()
    }


    @IBAction func textToSpeechAction(_ sender: Any) {
        print("clicked")

        if isSpeaking {
            guard let textContent = speechText else {
                speak(text: "")
                return
            }
            speak(text: textContent)

        } else {
            stopSpeech()
        }
        setImageForTextSpeech()
    }


}

然后我在collectionView的didEndDisplayingCell方法中调用该函数。

func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "detailArticleCell", for: indexPath) as! DetailArticleCell  
    cell.stopSpeech()
}

这仅适用于每三个细胞。但是我希望每次用户滑动到下一个单元格时语音停止。

1 个答案:

答案 0 :(得分:0)

更改此行:

let cell=collectionView.dequeueReusableCell(withReuseIdentifier: "detailArticleCell", for: indexPath) as! DetailArticleCell  

为:

if let detailCell = cell as? DetailArticleCell
{
     detailCell.stopSpeech()
}

看看会发生什么。

该委托方法已经为不再显示的单元格提供了参数,因此无需调用dequeueReusableCell(这可能会给您带来意想不到的东西)。