我想分析String
并检查其在系统发音期间是否包含某些关键词,例如“ 1分钟” 。
当AVSpeechSynthesizer
一次获取整个字符串并执行其操作时,我遇到了问题。在播放期间,我没有控制权来分析字符串以检查是否出现了这些关键字。
我的文本转语音代码如下:
func Speech() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
if !speechSynthesizer.isSpeaking {
self.VoiceString = self.VoiceString+self.DirectionsString
let speechUtterance = AVSpeechUtterance(string: self.VoiceString)
var voiceToUse: AVSpeechSynthesisVoice?
speechUtterance.voice = voiceToUse
speechUtterance.rate = Float(self.RangeSlider.selectedMinValue/2)
speechSynthesizer.speak(speechUtterance)
}
else {
speechSynthesizer.continueSpeaking()
}
animateActionButtonAppearance(shouldHideSpeakButton: true)
}
是否可以通过使用来检测特定的字符串
AVSpeechSynthesizer
还是您有其他方法?
答案 0 :(得分:3)
您应实现AVSpeechSynthesizer
的委托并添加以下代码:
var myText = "This is my text, which will be detect on text-to-speech operation"
override func viewDidLoad() {
super.viewDidLoad()
speechSynthesizer.delegate = self
}
已实现willSpeakRangeOfSpeechString
,它将按系统调用文本字符串中的每个口头单词。您可以实现String
类型的contains()
方法来检测文本中的特定字符串。
extension TextToSpeechVC: AVSpeechSynthesizerDelegate {
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let string = self.myText[characterRange.lowerBound..<characterRange.upperBound]
if string.trim == "operation" {
print("string = \(string)")
}
}
}
为范围的下标添加String
扩展名。
extension String {
var trim: String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
我希望这会对您有所帮助。