Skip to content

Instantly share code, notes, and snippets.

@GottaGetSwifty
Created June 18, 2024 14:53
Show Gist options
  • Save GottaGetSwifty/500e476e08f636a61e7deaa4a31458f8 to your computer and use it in GitHub Desktop.
Save GottaGetSwifty/500e476e08f636a61e7deaa4a31458f8 to your computer and use it in GitHub Desktop.
Fun example for abstracting delegate into a Type with a closure
import SwiftUI
import AVFoundation
class AVSpeechSynthGlue: NSObject, AVSpeechSynthesizerDelegate {
enum State {
case didStart(AVSpeechUtterance)
case willSpeakRangeOfSpeechString(NSRange)
case willSpeak(AVSpeechSynthesisMarker)
case didPause(AVSpeechUtterance)
case didContinue(AVSpeechUtterance)
case didFinish(AVSpeechUtterance)
case didCancel(AVSpeechUtterance)
}
let synth = AVSpeechSynthesizer()
let stateHandler: ((State) -> ())?
init(_ stateHandler: @escaping (State) -> ()) {
self.stateHandler = stateHandler
super.init()
synth.delegate = self
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart: AVSpeechUtterance) {
stateHandler?(.didStart(didStart))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString: NSRange, utterance: AVSpeechUtterance) {
stateHandler?(.willSpeakRangeOfSpeechString(willSpeakRangeOfSpeechString))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeak: AVSpeechSynthesisMarker, utterance: AVSpeechUtterance) {
stateHandler?(.willSpeak(willSpeak))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause: AVSpeechUtterance) {
stateHandler?(.didPause(didPause))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue: AVSpeechUtterance) {
stateHandler?(.didContinue(didContinue))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish: AVSpeechUtterance) {
stateHandler?(.didFinish(didFinish))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel: AVSpeechUtterance) {
stateHandler?(.didCancel(didCancel))
}
}
struct PodBay: View {
let synthGlue: AVSpeechSynthGlue = .init {
switch $0 {
case .didStart(let aVSpeechUtterance):
print("Started")
case .willSpeakRangeOfSpeechString(let nSRange):
print("spoke range")
case .willSpeak(let aVSpeechSynthesisMarker):
print("Will Speek")
case .didPause(let aVSpeechUtterance):
print("did Pause")
case .didContinue(let aVSpeechUtterance):
print("did continue")
case .didFinish(let aVSpeechUtterance):
print("did finish")
case .didCancel(let aVSpeechUtterance):
print("did cancel")
}
}
var synth: AVSpeechSynthesizer { synthGlue.synth }
var body: some View {
VStack(spacing: 16) {
Button("Open the Pod Bay doors") {
synth.speak(.init(string: "I'm sorry Dave, I'm afraid I can't do that"))
}
Button("Pause") {
synth.pauseSpeaking(at: .immediate)
}
Button("Continue") {
synth.continueSpeaking()
}
Button("Cancel") {
synth.stopSpeaking(at: .immediate)
}
}.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment