使用Flutter speech-to-text实现自定义药品词汇语音识别求助
解决Flutter speech-to-text识别自定义药品名称的方案
由于speech-to-text包底层依赖系统原生语音识别服务(Android的Google语音、iOS的Siri等),默认词典不包含罕见药品名时,需结合平台配置和代码逻辑双管齐下解决:
一、Android平台自定义词汇配置(8.0+)
系统允许通过配置文件向语音识别服务注入自定义词汇:
- 在
res/xml目录下创建voice_search.xml文件:
<?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/app_name" android:searchSuggestAuthority="com.google.android.googlequicksearchbox" android:includeInGlobalSearch="true"> <custom-voice-search android:keywords="@array/custom_medications" /> </searchable>
- 在
res/values/strings.xml中定义药品词汇数组:
<string-array name="custom_medications"> <item>XX特药1</item> <item>XX罕见药2</item> </string-array>
- 在
AndroidManifest.xml的主Activity中添加配置:
<activity ...> <meta-data android:name="android.app.searchable" android:resource="@xml/voice_search" /> </activity>
二、iOS平台自定义词汇配置
通过SiriKit的自定义词汇功能扩展识别范围:
- 创建
CustomVocabulary.plist文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>Identifier</key> <string>com.your.app.medications</string> <key>VocabularyItems</key> <array> <string>XX特药1</string> <string>XX罕见药2</string> </array> </dict> </array> </plist>
- 在
Info.plist中引入该配置:
<key>SiriCustomVocabulary</key> <array> <dict> <key>VocabularyIdentifier</key> <string>com.your.app.medications</string> <key>VocabularyFileName</key> <string>CustomVocabulary</string> </dict> </array>
三、Flutter代码层补充优化
即使平台配置生效,仍需代码兜底匹配:
- 开启实时部分识别结果,优先匹配自定义词汇库:
import 'package:speech_to_text/speech_to_text.dart' as stt; final stt.SpeechToText _speech = stt.SpeechToText(); // 可从本地存储/服务器拉取用户常用药品列表 List<String> customMedList = ["XX特药1", "XX罕见药2"]; void startVoiceInput() { _speech.listen( onResult: (result) { String rawText = result.recognizedWords.toLowerCase(); // 遍历匹配自定义词汇 for (var med in customMedList) { if (rawText.contains(med.toLowerCase())) { // 直接返回匹配到的药品名 handleMedRecognition(med); return; } } // 无匹配时使用原始结果 handleMedRecognition(rawText); }, partialResults: true, // 开启实时返回部分结果 localeId: 'zh_CN', // 对应目标语言 ); } void handleMedRecognition(String medName) { // 处理识别后的药品名逻辑 }
- 离线识别备选方案:
如果系统语音识别仍无法满足需求,可集成pocketsphinx_flutter离线语音包,自定义词典(.dic)和语言模型,完全掌控识别规则。
四、额外优化点
- 允许用户手动录入常用药品,构建个性化词汇库,识别时优先匹配
- 对识别结果做模糊匹配(比如计算编辑距离),找出最接近的自定义药品名
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

