如果之前集合到HelloWorld的项目还不会的话,请点击这个链接查看文章百度语音识别集成到HelloWorld项目按步骤操作,因为这个项目是基于HelloWorld项目集成而来。
项目界面比较简单,能实现功能就行了。
布局代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start"
app:layout_constraintBottom_toTopOf="@+id/guideline2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline2" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stop"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline3" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/re"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline"
app:layout_constraintVertical_bias="0.307" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.3" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.7" />
</androidx.constraintlayout.widget.ConstraintLayout>
要实现功能我们只需要MainActivity.class加上自己定义方法的代码就可以了
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.aip.asrwakeup3.core.mini.ActivityMiniRecog;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements com.baidu.speech.EventListener {
protected TextView tv_result;
protected Button btn_stop, btn_start;
private EventManager asr;
private void start() {
Map<String, Object> params = new LinkedHashMap<>();//传递Map的参数,会将Map自动序列化为json
String event = null;
event = SpeechConstant.ASR_START;
params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);//回调当前音量
String json = null;
json = new JSONObject(params).toString();//demo用json数据来做数据交换的方式
asr.send(event, json, null, 0, 0);// 初始化EventManager对象,这个实例只能创建一次,就是我们上方创建的asr,此处开始传入
}
private void stop() {
// tv_result.append("停止识别:ASR_STOP");
asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);//此处停止
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initPermission();
asr = EventManagerFactory.create(this, "asr");//注册自己的输出事件类
asr.registerListener(this);//调用 EventListener 中 onEvent方法
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
start();
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stop();
}
});
}
@Override
protected void onPause() {
super.onPause();
asr.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
}
@Override
protected void onDestroy() {
super.onDestroy();
asr.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
asr.unregisterListener(this);//推出事件管理器
// 必须与registerListener成对出现,否则可能造成内存泄露
}
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<>();
for (String perm : permissions) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
toApplyList.add(perm);
//进入这里代表没有权限
}
}
String[] tmplist = new String[toApplyList.size()];
if (!toApplyList.isEmpty()) {
ActivityCompat.requestPermissions(this, toApplyList.toArray(tmplist), 123);
}
}
private void initView() {
tv_result = findViewById(R.id.tv_result);
btn_start = findViewById(R.id.btn_start);
btn_stop = findViewById(R.id.btn_stop);
}
@Override
public void onEvent(String name, String params, byte[] data, int offset, int length) {
String resultTxt = null;
if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {//识别结果参数
if (params.contains("\"final_result\"")) {//语义结果值
try {
JSONObject json = new JSONObject(params);
resultTxt = json.getString("best_result");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (resultTxt != null) {
resultTxt += "\n";
tv_result.setText(resultTxt);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// 此处为android 6.0以上动态授权的回调,用户自行实现。
}
}