/// speak an utterance in `lang` language.
func speak(_ text: String, in lang: String = "en-GB") {
// โญ๏ธ setup utterance
let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: lang)
// โญ๏ธ speak utterance
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
import SwiftUI
import AVFoundation
struct SpeakButton: View {
let text: String
let language: Language
var body: some View {
Button { speak() } label: { buttonLabel }
}
}
extension SpeakButton {
enum Language: String {
case enGB = "en-GB"
case enUS = "en-US"
case zhTW = "zh-TW"
case zhCN = "zh-CN"
case zhHK = "zh-HK"
}
init(_ text:String, in lang: Language = .enGB) {
self.text = text
self.language = lang
}
static let synthesizer = AVSpeechSynthesizer()
/// speak an utterance.
func speak() {
// setup utterance
let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: language.rawValue)
// speak utterance
SpeakButton.synthesizer.speak(utterance)
}
/// button label
var buttonLabel: some View {
Text(text)
.fontWeight(.bold)
.font(.system(.headline, design: .rounded))
.padding()
.padding(.horizontal, 8)
.foregroundColor(.white)
.background(Color.purple)
.cornerRadius(8)
.shadow(radius: 4)
}
}
struct SpeakButton_Previews: PreviewProvider {
static var previews: some View {
VStack {
SpeakButton("Hello, Swift")
SpeakButton("May I help you?")
SpeakButton("May I help you?", in: .enUS)
SpeakButton("ไธปไบบ๏ผไปๆ่ฆไพ้ปไป้บผ๏ผ", in: .zhTW)
SpeakButton("ไธปไบบ๏ผไปๆ่ฆไพ้ปไป้บผ๏ผ", in: .zhHK)
}
}
}