雖然是實現Flutter的百度語音轉文字功能,主要還是通過Android端來實現百度語音轉文字功能,然後通過Flutter和Android端來傳資料(如下圖),來實現Flutter需求的功能。其中ios端也是可以實現百度語音轉文字的功能,但是因為我的電腦是window系統,所以不能用flutter來開發ios,所以我下面的教程主要是針對Android端的實現。
原則肯定是先看一下效果呀,例項為證: 百度語音轉漢字的時候一般都會在後面加一個句號。
1.新建一個flutter專案,來實現View端。
下圖紅色圓圈處不要打勾
2.新建android端的module
1.開啟flutter裡面的Android檔案
==找到flutter專案裡面的Android檔案,然後找到MainActivty,通過android studio,這裡爆紅不需要管他,開始build的時候可能會有點慢==。
開啟成功
1.新建一個module
記得選擇Android Library
。
名字自己命名吧,我取名為asr_plugin,不細說了。
新建成功
3.配置百度語音轉文字sdk
1.下載SDK
百度SDK下載地址:ai.baidu.com/sdk
2.在asr_plugin裡面配置SDK
1.找到core資料夾
2.把下圖檔案放到asr_plugin檔案的lib檔案中
不要忘記載入這個jar包
3.把jniLibs貼上到你的src檔案中
如圖所示:
把無用的包刪掉,只留下如圖中的so包
。
4.配置你的AndroidMainfest許可權
程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.asr_plugin">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
<!-- <service
android:name="com.baidu.speech.VoiceRecognitionService"
android:exported="false" />-->
<meta-data
android:name="com.baidu.speech.APP_ID"
android:value="15519387" />
<meta-data
android:name="com.baidu.speech.API_KEY"
android:value="Ywyh8ErHPQXBSapdQZqVBtdl" />
<meta-data
android:name="com.baidu.speech.SECRET_KEY"
android:value="DFPpDWnOGrNGzxfX07D5GFLryh3d3Nne" />
</application>
</manifest>
複製程式碼
有的同學可能會想把那個APP_ID,API_KEY,SECRET_KEY改為自己的應用,但是我在改為自己的應用的時候,出現了錯誤碼,具體是什麼錯誤,我也忘了,反正是關於我建立應用沒有語音轉文字這功能,個人提議,如果你不想麻煩的話,可以直接這些資料,如果你想配置自己的,也可以去嘗試一下,可以根據錯誤碼來檢視錯誤檔案,檢視錯誤碼的網址:ai.baidu.com/ai-doc/SPEE…
5.在flutter的Android檔案的build.gradle檔案裡面載入asr_plugin庫
此功能主要把asr_plugin載入到flutter裡面,方便等下進行資料通訊。 還需要一步,記得在
4.建立flutter和Android端的橋樑
1.配置flutter端的MethodChannel
建立一個asr_manager檔案,通過MethodChannel 來進行通訊。總共有三種通訊方式,我們這裡是屬於方法通訊。 總共有三個方法:開始錄音、停止錄音、取消錄音。 程式碼如下:
import 'package:flutter/services.dart';
class AsrManager {
static const MethodChannel _channel = const MethodChannel('asr_plugin');
///開始錄音
static Future<String> start({Map params}) async {
return await _channel.invokeMethod('start', params ?? {});
}
///停止錄音
static Future<String> stop() async {
return await _channel.invokeMethod('stop');
}
///取消錄音
static Future<String> cancel() async {
return await _channel.invokeMethod('cancel');
}
}
複製程式碼
2.配置Android端的MethodChannel
這些檔案除了AsrPlugin,其他你可以在你下載的那個百度SDK裡面找到,但是有一些需要修改的地方。
這些檔案你可以自己去下面我的百度網盤處下載
,應該都是適配的:
連結:pan.baidu.com/s/1ODBeSEBf…
提取碼:gnkq
關於AsrPlugin檔案,需要在Android端配置Flutter的環境: 在build.gradle檔案中加入如圖中程式碼:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
複製程式碼
flutter {
source '../..'
}
複製程式碼
配置成功之後,我們就可以實現Android端可以使用flutter的檔案了。 如果你沒用配置好這個環境的話,你就不能實現Android端與flutter端的通訊,用下面程式碼來實現與flutter的start,stop,cancel操作: 程式碼如下:
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Map;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class AsrPlugin implements MethodChannel.MethodCallHandler {
private final static String TAG = "AsrPlugin";
private final Activity activity;
private ResultStateful resultStateful;
private AsrManager asrManager;
public static void registerWith(Activity activity, BinaryMessenger messenger) {
MethodChannel channel = new MethodChannel(messenger, "asr_plugin");
AsrPlugin instance = new AsrPlugin(activity);
channel.setMethodCallHandler(instance);
}
public AsrPlugin(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
initPermission();
switch (methodCall.method) {
case "start":
resultStateful = ResultStateful.of(result);
start(methodCall, resultStateful);
break;
case "stop":
stop(methodCall,result);
break;
case "cancel":
cancel(methodCall,result);
break;
default:
result.notImplemented();
}
}
private void start(MethodCall call, ResultStateful result) {
if (activity == null) {
Log.e(TAG, "Ignored start, current activity is null.");
result.error("Ignored start, current activity is null.", null, null);
return;
}
if (getAsrManager() != null) {
getAsrManager().start(call.arguments instanceof Map ? (Map) call.arguments : null);
} else {
Log.e(TAG, "Ignored start, current getAsrManager is null.");
result.error("Ignored start, current getAsrManager is null.", null, null);
}
}
private void stop(MethodCall call, MethodChannel.Result result) {
if (asrManager != null) {
asrManager.stop();
}
}
private void cancel(MethodCall call, MethodChannel.Result result) {
if (asrManager != null) {
asrManager.cancel();
}
}
@Nullable
private AsrManager getAsrManager() {
if (asrManager == null) {
if (activity != null && !activity.isFinishing()) {
asrManager = new AsrManager(activity, onAsrListener);
}
}
return asrManager;
}
/**
* android 6.0 以上需要動態申請許可權
*/
private void initPermission() {
String permissions[] = {Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.INTERNET,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
ArrayList<String> toApplyList = new ArrayList<String>();
for (String perm :permissions){
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(activity, perm)) {
toApplyList.add(perm);
//進入到這裡代表沒有許可權.
}
}
String tmpList[] = new String[toApplyList.size()];
if (!toApplyList.isEmpty()){
ActivityCompat.requestPermissions(activity, toApplyList.toArray(tmpList), 123);
}
}
private OnAsrListener onAsrListener = new OnAsrListener() {
@Override
public void onAsrReady() {
}
@Override
public void onAsrBegin() {
}
@Override
public void onAsrEnd() {
}
@Override
public void onAsrPartialResult(String[] results, RecogResult recogResult) {
}
@Override
public void onAsrOnlineNluResult(String nluResult) {
}
@Override
public void onAsrFinalResult(String[] results, RecogResult recogResult) {
if (resultStateful != null) {
resultStateful.success(results[0]);
}
}
@Override
public void onAsrFinish(RecogResult recogResult) {
}
@Override
public void onAsrFinishError(int errorCode, int subErrorCode, String descMessage, RecogResult recogResult) {
if (resultStateful != null) {
resultStateful.error(descMessage, null, null);
}
}
@Override
public void onAsrLongFinish() {
}
@Override
public void onAsrVolume(int volumePercent, int volume) {
}
@Override
public void onAsrAudio(byte[] data, int offset, int length) {
}
@Override
public void onAsrExit() {
}
@Override
public void onOfflineLoaded() {
}
@Override
public void onOfflineUnLoaded() {
}
};
}
複製程式碼
3.在flutter的Android檔案中配置打包環境
主要為了避免環境衝突而導致功能不成功,配置如圖所示:
程式碼如下:
ndk {
abiFilters "armeabi-v7a","arm64-v8a","x86_64","x86" /*只打包flutter所支援的架構,flutter沒有armeabi架構的so,加x86的原因是為了能夠相容模擬器 abiFilters "armeabi-v7a" release 時打"armeabi-v7包 */
}
複製程式碼
packagingOptions {
/* 確保app與asr_plugin都依賴的libflutter.so libapp.so merge時不衝突@https://github.com/card-io/card.io-Android-SDK/issues/186#issuecomment-427552552 */
pickFirst 'lib/x86_64/libflutter.so'
pickFirst 'lib/x86_64/libapp.so'
pickFirst 'lib/x86/libflutter.so'
pickFirst 'lib/arm64-v8a/libflutter.so'
pickFirst 'lib/arm64-v8a/libapp.so'
pickFirst 'lib/armeabi-v7a/libapp.so'
}
複製程式碼
5.註冊plugin,實現通訊功能
主要是在flutter的android資料夾中呼叫我們上面建立的android的module裡面通訊檔案AsrPlugin,然後用來通訊資料通訊,達到我們所需要的效果。
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.example.asr_plugin.AsrPlugin;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
//flutter sdk >= v1.17.0 時使用下面方法註冊自定義plugin
AsrPlugin.registerWith(this, flutterEngine.getDartExecutor().getBinaryMessenger());
}
@Override
protected void onCreate(Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
}
}
複製程式碼
6.最後,編寫一個dart介面來展示效果
程式碼如圖所示:
import 'package:flutter/material.dart';
import 'asr_manager.dart';
void main(){
runApp(MaterialApp(
home: SpeakPage(),
));
}
///語音識別
class SpeakPage extends StatefulWidget {
@override
_SpeakPageState createState() => _SpeakPageState();
}
class _SpeakPageState extends State<SpeakPage>
with SingleTickerProviderStateMixin {
String speakTips = '長按說話';
String speakResult = '';
String result='故宮門票\n北京一日遊\n迪士尼樂園';
Animation<double> animation;
AnimationController controller;
@override
void initState() {
controller = AnimationController(
vsync: this, duration: Duration(milliseconds: 1000));
animation = CurvedAnimation(parent: controller, curve: Curves.easeIn)
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reverse();
} else if (status == AnimationStatus.dismissed) {
controller.forward();
}
});
super.initState();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.all(30),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[_topItem(), _bottomItem()],
),
),
),
);
}
_speakStart() {
controller.forward();
setState(() {
speakTips = '- 識別中 -';
});
AsrManager.start().then((text) {
if (text != null && text.length > 0) {
setState(() {
speakResult = text;
result=speakResult;
});
/*Navigator.pop(context);
Navigator.push(context,MaterialPageRoute(builder: (context)=> SearchPage(
keyword: speakResult,
)));*/
print("錯誤" + text);
}
}).catchError((e) {
print("----------123" + e.toString());
});
}
_speakStop() {
setState(() {
speakTips = '長按說話';
});
controller.reset();
controller.stop();
AsrManager.stop();
}
_topItem() {
return Column(
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
child: Text('你可以這樣說',
style: TextStyle(fontSize: 16, color: Colors.black54))),
Text(result,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
color: Colors.grey,
)),
Padding(
padding: EdgeInsets.all(20),
child: Text(
speakResult,
style: TextStyle(color: Colors.blue),
),
)
],
);
}
_bottomItem() {
return FractionallySizedBox(
widthFactor: 1,
child: Stack(
children: <Widget>[
GestureDetector(
onTapDown: (e) {
_speakStart();
},
onTapUp: (e) {
_speakStop();
},
onTapCancel: () {
_speakStop();
},
child: Center(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Text(
speakTips,
style: TextStyle(color: Colors.blue, fontSize: 12),
),
),
Stack(
children: <Widget>[
Container(
//佔坑,避免動畫執行過程中導致父佈局大小變得
height: MIC_SIZE,
width: MIC_SIZE,
),
Center(
child: AnimatedMic(
animation: animation,
),
)
],
)
],
),
),
),
Positioned(
right: 0,
bottom: 20,
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(
Icons.close,
size: 30,
color: Colors.grey,
),
),
)
],
),
);
}
}
const double MIC_SIZE = 80;
class AnimatedMic extends AnimatedWidget {
static final _opacityTween = Tween<double>(begin: 1, end: 0.5);
static final _sizeTween = Tween<double>(begin: MIC_SIZE, end: MIC_SIZE - 20);
AnimatedMic({Key key, Animation<double> animation})
: super(key: key, listenable: animation);
@override
Widget build(BuildContext context) {
final Animation<double> animation = listenable;
return Opacity(
opacity: _opacityTween.evaluate(animation),
child: Container(
height: _sizeTween.evaluate(animation),
width: _sizeTween.evaluate(animation),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(MIC_SIZE / 2),
),
child: Icon(
Icons.mic,
color: Colors.white,
size: 30,
),
),
);
}
}
複製程式碼
步驟可能畢竟多,我可能有也很多沒用考慮的地方哦,如果遇到問題可以提出來,這個功能的實現主要來自我學習flutter視訊的那個老師,老師部落格地址:blog.csdn.net/fengyuzheng…