トップ 最新 追記

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2023-11-11 [Android] TextToSpeech

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)
    }
}

_ 【ソースコード】

GitHubからどうぞ。
https://github.com/murakami/workbook/tree/master/android/TextToSpeech - GitHub

トップ 最新 追記