Created
November 14, 2019 07:16
-
-
Save yycking/834e84cb08771c062c105689b9c358d1 to your computer and use it in GitHub Desktop.
AVSpeechSynthesisVoice test
This file contains hidden or 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
//: A Cocoa based Playground to present user interface | |
import AVFoundation | |
let voices = AVSpeechSynthesisVoice.speechVoices().reduce([String:[AVSpeechSynthesisVoice]]()) { (result, voice) -> [String:[AVSpeechSynthesisVoice]] in | |
var voices = result | |
let locale = Locale(identifier: voice.language) | |
let code = locale.localizedString(forLanguageCode: locale.languageCode!) ?? "??" | |
var voiceOnLanguage = voices[code] ?? [] | |
voiceOnLanguage.append(voice) | |
voices[code] = voiceOnLanguage | |
return voices | |
} | |
let languages = voices.keys.map{String($0)} | |
extension AVSpeechSynthesisVoice { | |
func speech(text: String) { | |
let utterance = AVSpeechUtterance(string: text) | |
utterance.voice = self | |
let synth = AVSpeechSynthesizer() | |
synth.speak(utterance) | |
} | |
} | |
import SwiftUI | |
struct ContentView: View { | |
@State private var selectedLanguage = languages.first! | |
@State private var selectedVoice = voices[languages.first!]!.first! | |
@State private var text = """ | |
hello, world | |
你好,世界! | |
Hallo Welt! | |
¡Hola, mundo! | |
今日は、世界 | |
""" | |
var body: some View { | |
VStack { | |
Picker(selection: $selectedLanguage, label: Text("language")) { | |
ForEach(languages, id: \.self) { (language) in | |
Text(language) | |
} | |
} | |
Picker(selection: $selectedVoice, label: Text("voice")) { | |
ForEach(voices[selectedLanguage]!, id: \.self) { (voice) in | |
Text(voice.name) | |
} | |
} | |
TextField("text", text: $text).lineLimit(5) | |
Button("speech") { | |
self.selectedVoice.speech(text: self.text) | |
} | |
} | |
} | |
} | |
import PlaygroundSupport | |
PlaygroundPage.current.setLiveView(ContentView()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment