1.程序入口XML
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="activitytest.example.com.speechtest"> <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.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:usesCleartextTraffic="true" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.baidu.speech.APP_ID" android:value="15626306" /> <meta-data android:name="com.baidu.speech.API_KEY" android:value="IH4YSdWRFPIf1wRG5TWDgWlg" /> <meta-data android:name="com.baidu.speech.SECRET_KEY" android:value="V3IwR07NROBwXBdIPinpDgRGnECZpMbc" /> <service android:name="com.baidu.speech.VoiceRecognitionService" android:exported="false" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>2.需要添加的权限
<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.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />3.需要添加的百度接口授权配置文件
<meta-data android:name="com.baidu.speech.APP_ID" android:value="15626306" /> <meta-data android:name="com.baidu.speech.API_KEY" android:value="IH4YSdWRFPIf1wRG5TWDgWlg" /> <meta-data android:name="com.baidu.speech.SECRET_KEY" android:value="V3IwR07NROBwXBdIPinpDgRGnECZpMbc" /> <service android:name="com.baidu.speech.VoiceRecognitionService" android:exported="false" />4.主程序入口界面XML(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/txtResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textSize="18dp" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#999" /> <TextView android:layout_weight="1" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textSize="18dp" /> <Button android:layout_gravity="end" android:id="@+id/btn_stop" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="停止" /> <Button android:id="@+id/btn" android:layout_gravity="end" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="按住开始识别" /> </LinearLayout>5.主程序MainActivity代码
package activitytest.example.com.speechtest; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; 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 txtResult; protected Button btn; protected Button stopBtn; private EventManager asr; private Context mContext; private void start(){ Toast.makeText(mContext, "请开始说话", Toast.LENGTH_SHORT).show(); Map<String,Object> params = new LinkedHashMap<>();//传递Map<String,Object>的参数,会将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(){ txtResult.append("停止识别:ASR_STOP"); asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);//此处停止 } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext=this; initView(); initPermission(); asr = EventManagerFactory.create(this,"asr");//注册自己的输出事件类 asr.registerListener(this); 调用 EventListener 中 onEvent方法 btn.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: start(); /*mStartSpeechButton.setBackgroundResource( R.drawable.bdspeech_btn_orangelight_pressed);*/ break; case MotionEvent.ACTION_UP: stop(); /*mStartSpeechButton.setBackgroundResource( R.drawable.bdspeech_btn_orangelight_normal);*/ break; default: return false; } return true; } }); } @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成对出现,否则可能造成内存泄露 } 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); String result = json.getString("best_result");//取得key的识别结果 resultTxt = result; } catch (JSONException e) { e.printStackTrace(); } } } if (resultTxt != null){ resultTxt += "\n"; txtResult.append(resultTxt); } } private void initView() { txtResult = findViewById(R.id.txtResult); btn = findViewById(R.id.btn); stopBtn = findViewById(R.id.btn_stop); } 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(this, perm)) { toApplyList.add(perm); //进入到这里代表没有权限. } } String tmpList[] = new String[toApplyList.size()]; if (!toApplyList.isEmpty()){ ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { // 此处为android 6.0以上动态授权的回调,用户自行实现。 } }适合小白的一个demo
源码下载地址