分析iOS中文本到语音转换的字符串

时间:2019-03-06 03:54:07

标签: ios swift text-to-speech avspeechsynthesizer

我想分析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还是您有其他方法?

1 个答案:

答案 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])
    }
}

我希望这会对您有所帮助。