1
我有一個啓用分頁的集合視圖。我正在使用AVSpeechSynthesizer將文本轉換爲集合視圖的單元格中的語音。當我從一個單元格滑動到另一個單元格時,我希望語音停止。現在我正在調用在單元類中聲明的stopSpeech函數。SpeechUtterance不停止
//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()
}
這隻適用於每第三個細胞。但是我希望當用戶每次滑動到下一個單元格時都會停止語音。
Ashiq Sulaiman:每次在一個屏幕上顯示多少個單元格? – Hooda
@hooda只有一個單元格。它啓用了分頁功能。 –
爲什麼你使用** cell.stopSpeech()而不是** stopSpeech()**? – Hooda