Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

Flutter:后台自定义语音机器人,如谷歌助手或 SIRI。

Posted on 2022-05-30

在本教程中,我们将为语音机器人创建一个应用程序,它将在后台或前台收听语音并回答提交的查询。
我将只关注 Android,因为我从未在 iOS 中测试应用程序(没有足够的钱)。

让我们开始编码-

1)首先像这样创建一个新的flutter应用程序
新应用程序
2) 在您的pubspec.yaml文件中添加以下包:

 - flutter_tts: ^3.3.3 (use for text to speech) - flutter_background_service: ^2.1.0 (use for handling app in background) - speech_to_text: (use for speech to text)

3)。安卓配置:

`在您的 android/app/build.gradle 文件中将最低 Android SDK 版本更改为 21(或更高)。

minSdkVersion 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"/>

4)现在在终端中运行命令
flutter pub get

5)现在在同一目录中创建一个名为“background_service.dart”的新文件。

6)我们将首先设置后台处理,所以在新文件中编写以下代码,最重要的是忘记导入所有需要的文件。

 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 // We have to register the plugin manually if (service is AndroidServiceInstance) { service.on('setAsForeground').listen((event) { //set as foreground service.setAsForegroundService(); }); service.on('setAsBackground').listen((event) async { //set as background service.setAsBackgroundService(); }); } service.on('stopService').listen((event) { service.stopSelf(); }); // bring to foreground Timer.periodic(const Duration(seconds:1), (timer) async { if (service is AndroidServiceInstance) { service.setForegroundNotificationInfo( title: "My App Service", content: "Updated at ${DateTime.now()}", ); } /// you can see this log in logcat print('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}'); // test using external plugin service.invoke( 'update', { "current_date": DateTime.now().toIso8601String(), "last_message": '_lastWords', }, ); }); }

现在应用程序将在后台模式下工作。

7)现在让我们设置语音监听器和机器人进行重播,
假设当用户说“我想要帮助”或包含“帮助”关键字的内容时,系统会回复
**“我们正在发送帮助”** 或用户在说“停止”后停止监听器。

现在在同一个文件中添加以下代码。

 final SpeechToText _speechToText = SpeechToText(); bool _speechEnabled = false; String _lastWords="Say something"; void _initSpeech() async { _speechEnabled = await _speechToText.initialize(); } void _startListening() async { await _speechToText.listen(onResult: _onSpeechResult); } void _stopListening() async { await _speechToText.stop(); } Future<void> _onSpeechResult(SpeechRecognitionResult result) async { var flutterTts = FlutterTts(); _lastWords=(result.recognizedWords.toString().toLowerCase()); if(_lastWords.contains("hello") || _lastWords.contains('help')) { flutterTts.speak("We are sending help"); } else if(_lastWords.contains('stop')) { _stopListening(); flutterTts.speak("Stopped"); } }

8)现在让我们在后台听声音
在函数initializeService()的开头添加以下行
_initSpeech();
并在onStart()函数中的 Timer.periodic 函数之后添加这些行。
if (_speechEnabled) {
_startListening();
}

9)让我们创建一个 UI,在main.dart添加以下代码:

 import 'dart:async'; import 'package:flutter_background_service/flutter_background_service.dart' show AndroidConfiguration, FlutterBackgroundService, IosConfiguration, ServiceInstance; import 'package:flutter/material.dart'; import 'background_service.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await initializeService(); runApp( const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key,}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String text = "Stop Service"; @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text("Voice Bot"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ //for listen Continuous change in foreground we will be using Stream builder StreamBuilder<Map<String, dynamic>?>( stream: FlutterBackgroundService().on('update'), builder: (context,snapshot){ if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator(), ); } final data = snapshot.data!; String? lastMessage = data["last_message"]; DateTime? date = DateTime.tryParse(data["current_date"]); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(lastMessage ?? 'Unknown'), Text(date.toString()), ], ); }), Padding( padding: const EdgeInsets.all(8.0), child: GestureDetector( child: Container( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), decoration: BoxDecoration( color: Colors.blueAccent, borderRadius: BorderRadius.circular(16) ), child: const Text("Foreground Mode",style: TextStyle( color: Colors.white ),)), onTap: () { FlutterBackgroundService().invoke("setAsForeground"); }, ), ), Padding( padding: const EdgeInsets.all(8.0), child: GestureDetector( child: Container( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), decoration: BoxDecoration( color: Colors.blueAccent, borderRadius: BorderRadius.circular(16) ), child: const Text("Background Mode",style: TextStyle( color: Colors.white ),)), onTap: () { print('start'); FlutterBackgroundService().invoke("setAsBackground"); }, ), ), Padding( padding: const EdgeInsets.all(8.0), child: GestureDetector( child: Container( padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 20), decoration: BoxDecoration( color: Colors.blueAccent, borderRadius: BorderRadius.circular(16) ), child: Text(text,style: const TextStyle( color: Colors.white ),), ), onTap: () async { final service=FlutterBackgroundService(); var isRunning = await service.isRunning(); if (isRunning) { service.invoke("stopService"); } else { service.startService(); } if (!isRunning) { text = 'Stop Service'; } else { text = 'Start Service'; } setState(() {}); }, ), ), ], ), ), ), ); } }

10) 万岁应用程序完成…

文本
让我们编译并玩得开心。

图片说明

GitHub 回购:点击这里

原文: https://dev.to/djsmk123/fluttercustom-voice-bot-in-background-like-google-assistant-or-siri-bm9

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Christopher Butler
  • Colin Percival
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Dustin Curtis
  • eighty twenty
  • Elad Gil
  • Ellie Huxtable
  • Ethan Dalool
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Liz Danzico
  • Lou Plummer
  • Luke Wroblewski
  • Matt Baer
  • Matt Stoller
  • Matthias Endler
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Rohit Patel
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • Sam Rose
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Steve Blank
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • thesephist
  • Thinking Deep & Wide
  • Tim Kellogg
  • Understanding AI
  • Wes Kao
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme