1. 程式人生 > >android上使用藍牙設備進行語音輸入

android上使用藍牙設備進行語音輸入

view return 對話 nvi pat 顯示 you esc 註意

主要實現步驟如下:
1.確保已經和藍牙耳機配對連接上。
2.開啟藍牙信道
AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setBluetoothScoOn(true);
mAudioManager.startBluetoothSco();
3.開啟語音識別
4.退出時關閉藍牙信道
mAudioManager.setBluetoothScoOn(false);
mAudioManager.stopBluetoothSco();
5.額外需要添加的權限:
<uses-permission android:name="android.permission.BROADCAST_STICKY" /> 註:部分手機如無此權限會報錯
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

以上方法到android5.0以上可能無用

提供另外一種方法

  1. package com.example.dkdh.testrecord;
  2. import android.app.Activity;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothHeadset;
  6. import android.bluetooth.BluetoothProfile;
  7. import android.content.BroadcastReceiver;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.media.AudioManager;
  12. import android.media.MediaPlayer;
  13. import android.media.MediaRecorder;
  14. import android.os.Bundle;
  15. import android.os.Environment;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.Button;
  19. import android.widget.TextView;
  20. import android.widget.Toast;
  21. import com.example.dkdh.testrecord.util.FucUtil;
  22. import com.example.dkdh.testrecord.util.JsonParser;
  23. import com.iflytek.cloud.InitListener;
  24. import com.iflytek.cloud.RecognizerListener;
  25. import com.iflytek.cloud.RecognizerResult;
  26. import com.iflytek.cloud.SpeechConstant;
  27. import com.iflytek.cloud.SpeechError;
  28. import com.iflytek.cloud.SpeechRecognizer;
  29. import com.iflytek.cloud.SpeechUtility;
  30. import com.iflytek.cloud.ErrorCode;
  31. import java.io.IOException;
  32. import java.util.HashMap;
  33. import java.util.LinkedHashMap;
  34. import java.util.List;
  35. public class MainActivity extends Activity implements View.OnClickListener{
  36. private final String TAG = MainActivity.class.getSimpleName();
  37. private final String XF_APP_ID = "xxxxxx";
  38. BluetoothHeadset headset;
  39. private Button start,stop;
  40. private TextView result;
  41. private AudioManager mAudioManager = null;
  42. private BluetoothHeadset mBluetoothHeadset;
  43. private BluetoothAdapter mBluetoothAdapter;
  44. private BluetoothDevice mBluetoothDevice;
  45. private SpeechRecognizer mIat;
  46. // // 語音聽寫UI
  47. // private RecognizerDialog mIatDialog;
  48. // // 用HashMap存儲聽寫結果
  49. private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
  50. @Override
  51. protected void onCreate(Bundle savedInstanceState) {
  52. super.onCreate(savedInstanceState);
  53. setContentView(R.layout.activity_main);
  54. SpeechUtility.createUtility(this, SpeechConstant.APPID + "=" + XF_APP_ID);
  55. result = (TextView)findViewById(R.id.result);
  56. start = (Button)findViewById(R.id.startRec);
  57. stop = (Button)findViewById(R.id.stopRec);
  58. start.setOnClickListener(this);
  59. stop.setOnClickListener(this);
  60. mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  61. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  62. mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);
  63. // // 初始化識別無UI識別對象
  64. // // 使用SpeechRecognizer對象,可根據回調消息自定義界面;第二個參數:本地識別時傳mInitListener
  65. mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
  66. }
  67. private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener(){
  68. @Override
  69. public void onServiceConnected(int profile, BluetoothProfile proxy) {
  70. if (profile == BluetoothProfile.HEADSET){
  71. mBluetoothHeadset = (BluetoothHeadset) proxy;
  72. List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
  73. if (devices.size()>0){
  74. mBluetoothDevice = devices.get(0);
  75. int state = mBluetoothHeadset.getConnectionState(mBluetoothDevice);
  76. Log.e("==============","headset state:"+state);
  77. if (state==BluetoothHeadset.STATE_CONNECTED){
  78. Log.e("=================","bluetooth headset connected");
  79. }
  80. }
  81. }
  82. }
  83. @Override
  84. public void onServiceDisconnected(int profile) {
  85. if (profile == BluetoothProfile.HEADSET){
  86. mBluetoothHeadset = null;
  87. }
  88. }
  89. };
  90. @Override
  91. public void onClick(View v) {
  92. switch (v.getId()){
  93. case R.id.startRec:
  94. startRecordWav();
  95. break;
  96. case R.id.stopRec:
  97. stopRecordWav();
  98. break;
  99. default:
  100. break;
  101. }
  102. }
  103. /**
  104. * 識別實時語音
  105. */
  106. private void recog(){
  107. mIatResults.clear();
  108. // 設置參數
  109. setParam();
  110. int ret = 0;
  111. // 不顯示聽寫對話框
  112. ret = mIat.startListening(mRecognizerListener);
  113. if (ret != ErrorCode.SUCCESS) {
  114. showTip("聽寫失敗,錯誤碼:" + ret);
  115. } else {
  116. // showTip("");
  117. }
  118. }
  119. /**
  120. * 初始化監聽器。
  121. */
  122. private InitListener mInitListener = new InitListener() {
  123. @Override
  124. public void onInit(int code) {
  125. Log.i(TAG, "SpeechRecognizer init() code = " + code);
  126. if (code != ErrorCode.SUCCESS) {
  127. showTip("初始化失敗,錯誤碼:" + code);
  128. }
  129. }
  130. };
  131. /**
  132. * 聽寫監聽器。
  133. */
  134. private RecognizerListener mRecognizerListener = new RecognizerListener() {
  135. @Override
  136. public void onBeginOfSpeech() {
  137. // 此回調表示:sdk內部錄音機已經準備好了,用戶可以開始語音輸入
  138. showTip("開始說話");
  139. }
  140. @Override
  141. public void onError(SpeechError error) {
  142. // Tips:
  143. // 錯誤碼:10118(您沒有說話),可能是錄音機權限被禁,需要提示用戶打開應用的錄音權限。
  144. showTip(error.getPlainDescription(true));
  145. // showTip("錯誤碼:10118(您沒有說話),可能是錄音機權限被禁,請打開應用的錄音權限。");
  146. }
  147. @Override
  148. public void onEndOfSpeech() {
  149. // 此回調表示:檢測到了語音的尾端點,已經進入識別過程,不再接受語音輸入
  150. showTip("結束說話");
  151. }
  152. @Override
  153. public void onResult(RecognizerResult results, boolean isLast) {
  154. String text = JsonParser.parseIatResult(results.getResultString());
  155. Log.i(TAG, text);
  156. showTip(text);
  157. if(isLast) {
  158. //TODO 最後的結果
  159. result.append(text);
  160. }
  161. }
  162. @Override
  163. public void onVolumeChanged(int volume, byte[] data) {
  164. // showTip("當前正在說話,音量大小:" + volume);
  165. Log.i(TAG,"當前正在說話,音量大小:" + volume);
  166. Log.i(TAG, "返回音頻數據:" + data.length);
  167. }
  168. @Override
  169. public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
  170. // 以下代碼用於獲取與雲端的會話id,當業務出錯時將會話id提供給技術支持人員,可用於查詢會話日誌,定位出錯原因
  171. // 若使用本地能力,會話id為null
  172. // if (SpeechEvent.EVENT_SESSION_ID == eventType) {
  173. // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
  174. // Log.d(TAG, "session id =" + sid);
  175. // }
  176. }
  177. };
  178. /**
  179. * Toast顯示提示
  180. */
  181. private void showTip(String str){
  182. Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
  183. }
  184. /**
  185. * 參數設置
  186. * @return
  187. */
  188. public void setParam(){
  189. // 清空參數
  190. mIat.setParameter(SpeechConstant.PARAMS, null);
  191. // 設置引擎
  192. mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
  193. // 設置返回結果格式
  194. mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
  195. // 設置語言
  196. mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
  197. // 設置語言區域
  198. mIat.setParameter(SpeechConstant.ACCENT,"mandarin");
  199. // 設置語音前端點:靜音超時時間,即用戶多長時間不說話則當做超時處理
  200. mIat.setParameter(SpeechConstant.VAD_BOS, "8000");
  201. // 設置語音後端點:後端點靜音檢測時間,即用戶停止說話多長時間內即認為不再輸入, 自動停止錄音
  202. mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
  203. // 設置標點符號,設置為"0"返回結果無標點,設置為"1"返回結果有標點
  204. mIat.setParameter(SpeechConstant.ASR_PTT, "0");
  205. // 設置音頻保存路徑,保存音頻格式支持pcm、wav,設置路徑為sd卡請註意WRITE_EXTERNAL_STORAGE權限
  206. // 註:AUDIO_FORMAT參數語記需要更新版本才能生效
  207. mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
  208. mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
  209. // 設置錄音時長,單位ms
  210. mIat.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT,"60000");
  211. //設置音頻源,MIC、VOICE_RECOGNITION、VOICE_COMMUNICATION可用,但與不同android系統有關
  212. mIat.setParameter(SpeechConstant.AUDIO_SOURCE, MediaRecorder.AudioSource.VOICE_COMMUNICATION+"");
  213. }
  214. /**
  215. * 停止錄音
  216. */
  217. private void stopRecordWav(){
  218. Log.e(TAG, "停止錄音");
  219. mBluetoothHeadset.stopVoiceRecognition(mBluetoothDevice);
  220. }
  221. /**
  222. * 錄音,自主控制錄音格式、速率等
  223. */
  224. private void startRecordWav(final int source){
  225. if (!mAudioManager.isBluetoothScoAvailableOffCall()) {
  226. Log.d(TAG, "系統不支持藍牙錄音");
  227. return;
  228. }
  229. if (mBluetoothHeadset == null){
  230. Toast.makeText(this, "藍牙耳機對象null",Toast.LENGTH_SHORT).show();
  231. return;
  232. }
  233. if (mBluetoothDevice!=null){
  234. mBluetoothHeadset.startVoiceRecognition(mBluetoothDevice);
  235. }
  236. IntentFilter audioStateFilter = new IntentFilter();
  237. audioStateFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
  238. audioStateFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
  239. registerReceiver(new BroadcastReceiver() {
  240. @Override
  241. public void onReceive(Context context, Intent intent) {
  242. String action = intent.getAction();
  243. if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)){
  244. int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,-1);
  245. if (state==BluetoothHeadset.STATE_AUDIO_CONNECTED){
  246. Log.e("==============","開始藍牙語音識別");
  247. recog();
  248. unregisterReceiver(this); // 別遺漏
  249. }
  250. }
  251. }
  252. },audioStateFilter);
  253. }
  254. @Override
  255. protected void onResume(){
  256. super.onResume();
  257. }
  258. }

android上使用藍牙設備進行語音輸入