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?

1
  • 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. Commented Jun 4, 2019 at 21:36

1 Answer 1

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()
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Do I need to specify a range or anything beyond :utterance?
@zztop Nope, I added a code example you can reference. You are not obligated to use any of the data passed in.
Thanks, that worked. If I want to cut off speech past a certain amount of words would this be the place to do it.
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: developer.apple.com/documentation/avfoundation/… After that, see if you have enough to take care of that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.