Created
June 12, 2020 13:05
-
-
Save Libranner/052de5f482da046deae0ad6b6bc1b8ef to your computer and use it in GitHub Desktop.
AVSpeechSynthesizer + SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import AVFoundation | |
struct ContentView: View { | |
var synthVM = SynthViewModel() | |
var body: some View { | |
VStack { | |
Text("This is Office Hours") | |
Button(action: { | |
self.synthVM.speak(text: "This is Office Hours. Thanks for your questions!") | |
}) { | |
Text("Play") | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
class SynthViewModel: NSObject { | |
private var speechSynthesizer = AVSpeechSynthesizer() | |
override init() { | |
super.init() | |
self.speechSynthesizer.delegate = self | |
} | |
func speak(text: String) { | |
let utterance = AVSpeechUtterance(string: text) | |
speechSynthesizer.speak(utterance) | |
} | |
} | |
extension SynthViewModel: AVSpeechSynthesizerDelegate { | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) { | |
print("started") | |
} | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) { | |
print("paused") | |
} | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {} | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {} | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {} | |
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { | |
print("finished") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment