语音识别

一个 Flutter 插件,用于使用语音识别(iOS10+ / Android 4.1+)。

安装

  1. 依赖它
    将此添加到您的 package 的 pubspec.yaml 文件中
dependencies:
  speech_recognition: "^0.2.0+1"
  1. 安装它
    您可以从命令行安装包
$ flutter packages get

或者,您的编辑器可能支持“packages get”。请查阅您的编辑器文档了解更多信息。

  1. 导入它
    现在,在您的 Dart 代码中,您可以使用
import 'package:speech_recognition/speech_recognition.dart';

用法

//..
_speech = new SpeechRecognition();

// The flutter app not only call methods on the host platform,
// it also needs to receive method calls from host.
_speech.setAvailabilityHandler((bool result) 
  => setState(() => _speechRecognitionAvailable = result));

// handle device current locale detection
_speech.setCurrentLocaleHandler((String locale) =>
 setState(() => _currentLocale = locale));

_speech.setRecognitionStartedHandler(() 
  => setState(() => _isListening = true));

// this handler will be called during recognition. 
// the iOS API sends intermediate results,
// On my Android device, only the final transcription is received
_speech.setRecognitionResultHandler((String text) 
  => setState(() => transcription = text));

_speech.setRecognitionCompleteHandler(() 
  => setState(() => _isListening = false));

// 1st launch : speech recognition permission / initialization
_speech
    .activate()
    .then((res) => setState(() => _speechRecognitionAvailable = res));
//..

speech.listen(locale:_currentLocale).then((result)=> print('result : $result'));

// ...

speech.cancel();

// ||

speech.stop();

识别

权限

iOS

infos.plist,添加

  • Privacy - Microphone Usage Description
  • Privacy - Speech Recognition Usage Description
<key>NSMicrophoneUsageDescription</key>
<string>This application needs to access your microphone</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>This application needs the speech recognition permission</string>

:warning: Swift 项目

此插件是用Swift编写的,因此要在Flutter/ObjC项目中使用,
您需要将项目转换为“Current swift syntax”(编辑/转换/Current swift syntax)

Android

<uses-permission android:name="android.permission.RECORD_AUDIO" />

限制

在iOS上,默认情况下,该插件已配置为支持法语、英语、俄语、西班牙语。
在Android上,如果没有额外的安装,它可能仅支持设备的默认区域设置。

GitHub

https://github.com/rxlabz/speech_recognition