본문 바로가기

Flutter

Flutter Voice to Text 음성입력.#2

class _VoiceToTextState extends State<VoiceToText> {
  SpeechToText speechToText = SpeechToText();
  String textVoice = " Click Hold for Speech to Text";
  bool isListening = false;

  @override
  void dispose() {
    speechToText.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: AvatarGlow(
        glowColor: Colors.blue,
        endRadius: 90.0,
        repeat: true,
        showTwoGlows: true,
        repeatPauseDuration: const Duration(milliseconds: 100),
        animate: isListening,
        duration: Duration(milliseconds: 2000),
        child: GestureDetector(
          onTapDown: (voice) async {
            if (!isListening) {
              var available = await speechToText.initialize();
              if (available) {
                setState(() {
                  isListening = true;
                  speechToText.listen(onResult: (result) {
                    setState(() {
                      //결과를 다시 setState해야 화면이 갱신된다.
                      textVoice = result.recognizedWords;
                    });
                  });
                });
              }
            }
          },
          onTapUp: (voice) async {
            setState(() {
              isListening = false;
            });
            speechToText.stop();
          },
          child: CircleAvatar(radius: 35, child: Icon(isListening ? Icons.mic : Icons.mic_none, color: Colors.white)),
        ),
      ),
      
      appBar: AppBar(title: Text('voice to Text')),
      body: Container(
        child: Center(child: Text(textVoice, style: const TextStyle(fontSize: 30))),
      ),
    );
  }
}

음성이 버틀 눌러서 isListening true 이면 setState 로 스피치 투 텍스트를 호출

그리고 스피치 투 텍스트도 setState 로 textVoice 를 갱신해야 화면에 표시된다.

 

마지막으로 싱글차일드스크롤 뷰로 긴글을 입력받을 수 있게 한다.

SingleChildScrollView(
        reverse: true,
        physics: const BouncingScrollPhysics(),
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          alignment: Alignment.center,
          child: Center(child: Text(textVoice, style: const TextStyle(fontSize: 30))),
        ),
      ),