[flutter] FloatingActionButton을 사용하여 음성 인식 기능 구현하기
음성 인식 기능을 갖춘 Flutter 앱을 개발하는 방법에 대해 알아보겠습니다. 이 기능은 사용자가 앱에 음성 명령을 내리면 그에 따라 작업을 수행할 수 있게 해줍니다.
1. 음성 인식 플러그인 추가하기
음성 인식 기능을 구현하기 위해 먼저 speech_to_text
플러그인을 추가해야 합니다. pubspec.yaml
파일을 열고 아래와 같이 플러그인을 추가합니다.
dependencies:
speech_to_text: ^5.0.0
이제 터미널에서 flutter pub get
명령을 실행하여 패키지를 다운로드하고 프로젝트를 업데이트합니다.
2. FloatingActionButton 추가하기
음성 인식 기능을 시작하는 버튼으로 FloatingActionButton을 추가합니다.
FloatingActionButton(
onPressed: () {
// 음성 인식 기능 시작
},
child: Icon(Icons.mic),
)
3. 음성 인식 기능 구현하기
음성 인식을 시작하고 결과를 처리하는 코드를 구현합니다.
import 'package:speech_to_text/speech_to_text.dart' as stt;
final stt.SpeechToText _speech = stt.SpeechToText();
void startListening() {
_speech.listen(
onResult: (stt.SpeechRecognitionResult result) {
if (result.finalResult) {
// 음성 인식 결과 처리
print(result.recognizedWords);
}
},
);
}
void stopListening() {
_speech.stop();
}
4. 권한 처리
음성 인식을 위해 권한을 요청하는 코드를 추가합니다.
void requestPermission() async {
bool available = await _speech.initialize(
onStatus: (status) => print('onStatus: $status'),
onError: (errorNotification) => print('onError: $errorNotification'),
);
if (available) {
// 권한 허용됨
} else {
// 권한 거부됨
}
}
마무리
이제 Flutter 앱에 음성 인식 기능을 구현할 수 있습니다. 사용자가 FloatingActionButton을 눌러 음성 인식을 시작하고, 그 결과를 처리할 수 있게 되었습니다.
참고 문헌:
이제 Flutter 앱에 음성 인식 기능을 구현할 수 있습니다. 사용자가 FloatingActionButton을 눌러 음성 인식을 시작하고, 그 결과를 처리할 수 있게 되었습니다.