read text aloud
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
public protocol SpeechServicing: AnyObject {
|
||||
/// Called when the text was read to the end; never after `stop()`.
|
||||
var onFinish: (() -> Void)? { get set }
|
||||
/// Reads `text` aloud with the system voice, cutting off anything still being read.
|
||||
func speak(_ text: String)
|
||||
func stop()
|
||||
}
|
||||
|
||||
/// Speech through `AVSpeechSynthesizer`.
|
||||
@MainActor
|
||||
public final class SpeechService: NSObject, SpeechServicing {
|
||||
public var onFinish: (() -> Void)?
|
||||
private lazy var synthesizer: AVSpeechSynthesizer = {
|
||||
let synthesizer = AVSpeechSynthesizer()
|
||||
synthesizer.delegate = self
|
||||
return synthesizer
|
||||
}()
|
||||
/// The utterance now being read; a late finish of a replaced one must not end the new one.
|
||||
private var current: ObjectIdentifier?
|
||||
|
||||
/// Nonisolated, so the shared `AppServices.live` can build it.
|
||||
override public nonisolated init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func speak(_ text: String) {
|
||||
stop()
|
||||
let utterance = AVSpeechUtterance(string: text)
|
||||
current = ObjectIdentifier(utterance)
|
||||
synthesizer.speak(utterance)
|
||||
}
|
||||
|
||||
public func stop() {
|
||||
current = nil
|
||||
synthesizer.stopSpeaking(at: .immediate)
|
||||
}
|
||||
}
|
||||
|
||||
extension SpeechService: AVSpeechSynthesizerDelegate {
|
||||
nonisolated public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
|
||||
let finished = ObjectIdentifier(utterance)
|
||||
Task { @MainActor in
|
||||
guard self.current == finished else { return }
|
||||
self.current = nil
|
||||
self.onFinish?()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user