ios - 在 iOS 中分析文本到语音的字符串

标签 ios swift text-to-speech avspeechsynthesizer

我想分析 String 并检查它是否包含某些关键字,例如 "1 minute" 在文本被系统发音时。

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)
}

Is it possible to detect specific string by using AVSpeechSynthesizer or have you any other approach?

最佳答案

您应该实现 AVSpeechSynthesizer 的委托(delegate)并添加以下代码:

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

希望对您有所帮助。

关于ios - 在 iOS 中分析文本到语音的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015292/

相关文章:

ios - 尝试对 UITableView 中的单元格重新排序时获取 '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'

ios - Parse 数据库中的随机项

swift - 是否可以从字符串实例化 SwiftUI View ?

c++ - 用 C++ 编写的高质量开源文本转语音 (TTS) 引擎

iphone - 点击按钮浏览动画的每一帧

iOS 在dispatch_async 中更新RLMObject

ios - UIApplicationOpenURLOptionsKey.sourceApplication 可以为零吗?

ios - 无法快速停止 UIView 动画

Android 文本转语音服务突然停止

android:如何在非 Activity 类上使用文本到语音