我有一个启用分页的集合视图。我正在使用 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()
}
这仅适用于每三个单元格。但是我希望当用户每次滑动到下一个单元格时声音停止。