有没有办法将AVSpeechBoundary设置为某个值或句子完成后?

时间:2017-04-25 05:33:07

标签: ios swift avfoundation

我想暂停语音说话,它必须完成它正在说出的当前句子然后它必须暂停,但API只提供两个暂停类型立即和单词不是当前句子。我试过这个,

 myutterance = AVSpeechUtterance(string:readTextView.text)

 synth .speak(myutterance)

 synth .pauseSpeaking(at: AVSpeechBoundary.immediate)

但是在文本完成后它会立即暂停。

1 个答案:

答案 0 :(得分:3)

我只是尝试了你所做的一切,并且在没有给出足够停顿的情况下阅读了整个句子,

let someText = "Some Sample text. That will read and pause after every sentence"

let speechSynthesizer = AVSpeechSynthesizer()

let myutterance = AVSpeechUtterance(string:someText)

speechSynthesizer .speak(myutterance)

//Normal reading without pause
speechSynthesizer .pauseSpeaking(at: AVSpeechBoundary.immediate)

要在每个句子后暂停,您可以将整个文本分解为简单的组件,并使用postUtteranceDelay属性在下面的循环中单独读取它们。

//To pause after every sentence
let components = someText.components(separatedBy: ".")

for str in components{

    let myutterance = AVSpeechUtterance(string:str)

    speechSynthesizer .speak(myutterance)

    myutterance.postUtteranceDelay = 1 //Set it to whatever value you would want.
}

要在完成当前说的句子后暂停,我们需要做一个小小的黑客,

var isPaused:Bool = false
let someText = "Some Sample text. That will read and pause after every sentence. The next sentence should'nt be heard if you had pressed the pause button. Let us try this."
let speechSynthesizer = AVSpeechSynthesizer()
var currentUtterance:AVSpeechUtterance?

override func viewDidLoad() {
    super.viewDidLoad()
    speechSynthesizer.delegate = self
}

@IBAction func startSpeaking(_ sender: Any) {

    //Pause after every sentence
    let components = someText.components(separatedBy: ".")

    for str in components{

        let myutterance = AVSpeechUtterance(string:str)

        speechSynthesizer .speak(myutterance)

        myutterance.postUtteranceDelay = 1
    }
}

@IBAction func pauseSpeaking(_ sender: Any) {
    isPaused = !isPaused
}

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance){
    print("location\(characterRange.location)")
    print("Range + Length\(characterRange.location + characterRange.length)")
    print("currentUtterance!.speechString\(currentUtterance!.speechString)")
    print("currentUtterance!.count\(currentUtterance!.speechString.characters.count)")

    if isPaused && (characterRange.location + characterRange.length) == currentUtterance!.speechString.characters.count{
        speechSynthesizer.stopSpeaking(at:.word)
    }

}

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance){
    currentUtterance = utterance
}