iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど
UIはJetpack Compose。
TextToSpeechインスタンスは外のメンバーとして保持し、setContent内がReact的なコンテンツとなるようだ。
class MainActivity : ComponentActivity(), TextToSpeech.OnInitListener {
private var textToSpeech: TextToSpeech? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.textToSpeech = TextToSpeech(this, this)
setContent {
TextToSpeechTheme {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting(this.textToSpeech)
}
}
}
}
onInit()で初期化を
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
val locale = Locale.JAPAN
if (this.textToSpeech!!.isLanguageAvailable(locale) >= TextToSpeech.LANG_AVAILABLE) {
this.textToSpeech!!.language = Locale.JAPAN
}
// this.tts!!.speak("こんにちは", TextToSpeech.QUEUE_FLUSH, null, "utteranceId")
}
}
}
入力フィールドとボタンのコンテンツ。
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Greeting(textToSpeech: TextToSpeech?, modifier: Modifier = Modifier) {
val textValue = rememberSaveable { mutableStateOf("文字列を入力してください。") }
Column {
TextField(
value = textValue.value,
onValueChange = { textValue.value = it },
label = { },
modifier = Modifier.padding(16.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Button(
onClick = {
if (textToSpeech != null) {
textToSpeech!!.speak(
textValue.value,
TextToSpeech.QUEUE_FLUSH,
null,
"utteranceId"
)
}
}
) {
Text("Say")
}
}
}
rememberSaveableで文章を永続的に保持し、入力フィールドの値をtextToSpeechに渡している。
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
TextToSpeechTheme {
Greeting(null)
}
}