0

This is stupid simple but I cannot get it to work.

I want to stop recording before the phone speaks something. No data is being passed.

let words = "Hello world"
let utt =  AVSpeechUtterance(string:words)
stopRecordingWithCompletion() {
    voice.speak(utt) 
}

func stopRecordinWithCompletion(closure: () -> Void) {
   recognitionRequest?.endAudio()
    recognitionRequest = nil
    recognitionTask?.cancel()
    recognitionTask = nil      
    let inputNode = audioEngine.inputNode
    let bus = 0
    inputNode?.removeTap(onBus: bus)
    self.audioEngine.stop()
    closure()
}

What am I doing wrong?

zztop
  • 701
  • 1
  • 7
  • 20
  • The speech is occurring before the recording stops. If recording is not first disabled, the system records its own speech. The voice.speak(utt) does not seem to be waiting for completion of the stopRecording method. – zztop Jun 04 '19 at 21:36

1 Answers1

1

Your current approach is not really ideal for this.

To begin with, AVSpeechSynthesizer provides a delegate you can monitor for changes, including when it is about to speak.

speechSynthesizer(_:willSpeakRangeOfSpeechString:utterance:)

Just observe this, and call your stop function. No closure is required since it is a synchronous function call.

In summary:

  1. Conform to AVSpeechSynthesizerDelegate
  2. Implement speechSynthesizer(_:willSpeakRangeOfSpeechString:utterance:)
  3. When the function above is called, have it call your stopRecording() function

An example of the delegate setup:

extension YourClassHere: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer,
                           willSpeakRangeOfSpeechString characterRange: NSRange,
                           utterance: AVSpeechUtterance) {
        stopRecording()
    }
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
  • Do I need to specify a range or anything beyond :utterance? – zztop Jun 04 '19 at 21:51
  • @zztop Nope, I added a code example you can reference. You are not obligated to use any of the data passed in. – CodeBender Jun 04 '19 at 21:55
  • Thanks, that worked. If I want to cut off speech past a certain amount of words would this be the place to do it. – zztop Jun 04 '19 at 22:01
  • yay... as to cutting off past a certain amount of words, you may be able to with some additional work. Going about that is outside the scope of this question & would typically be met with "ask a new question". I'd recommend you read this first: https://developer.apple.com/documentation/avfoundation/avspeechsynthesizerdelegate/1619681-speechsynthesizer After that, see if you have enough to take care of that. – CodeBender Jun 04 '19 at 22:05