gpt4 book ai didi

ios - 说话停不下来

转载 作者:行者123 更新时间:2023-11-28 08:03:56 25 4
gpt4 key购买 nike

我有一个启用了分页的 Collection View 。我正在使用 AVSpeechSynthesizer 在 Collection View 的单元格中进行文本到语音的转换。当我从一个单元格滑动到另一个单元格时,我希望声音停止。现在我正在调用在单元格类中声明的 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()
}

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

最佳答案

改变这一行:

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

到:

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

看看会发生什么。

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

关于ios - 说话停不下来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com