1 概述
我们将为语音机器人创建一个应用程序,该程序将监听后台或前台的语音,并将回答提交的查询。
2 开始编码
2.1 首先创建一个新的 flutter 应用程序
2.2 在 pubspec.yaml 文件中添加以下包
dependencies:
flutter:
sdk: flutter
flutter_tts: ^3.3.3
flutter_background_service: ^2.1.0
speech_to_text:
2.3 Android 配置
在 Android/app/build.gradle 文件中,将 Android SDK 的最小版本更改为21(或更高)。
注意: 针对 Android 11使用文本语音转换的应用程序应该在其清单的查询元素中声明 TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE
<queries>
<intent>
<action android:name="android.speech.RecognitionService"/>
</intent>
</queries>
在 android/app/src/main/AndroidManifest.xml 中添加以下内容:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
2.4 在终端运行 flutter pub get
命令
2.5 创建 background_service.dart 文件
final service = FlutterBackgroundService();
Future initializeService()async{
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will executed when app is in foreground or background in separated isolate
onStart: onStart,
// auto start service
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
await service.startService();
}
bool onIosBackground(ServiceInstance service) {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
return true;
}
void onStart(ServiceInstance service) async {
// Only available for flutter 3.0.0 and later
DartPluginRegistrant.ensureInitialized();
// For flutter prior to version 3.0.0