android語音辨識技術

來源:互聯網
上載者:User

         今天從網上找了個例子實現了語音辨識,個人感覺挺好玩的,就把代碼貼出來與大家分享下:

         Android中主要通過RecognizerIntent來實現語音辨識,其實代碼比較簡單,但是如果找不到設定,就會拋出異常ActivityNotFoundException,所以我們需要捕捉這個異常。而且語音辨識在模擬器上是無法測試的,因為語音辨識是訪問google雲端資料,所以如果手機的網路沒有開啟,就無法實現識別聲音的!一定要開啟手機的網路,如果手機不存在語音辨識功能的話,也是無法啟用識別!

        下面是RecognizerIntentActivity中的代碼:

        

public class RecognizerIntentActivity extends Activity {private Button btnReconizer;private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.reconizer);btnReconizer=(Button) this.findViewById(R.id.btnRecognizer);btnReconizer.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry{//通過Intent傳遞語音辨識的模式,開啟語音Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);//語言模式和自由模式的語音辨識intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);//提示音開始intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "開始語音");//開始語音辨識startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);}catch (Exception e) {// TODO: handle exceptione.printStackTrace();Toast.makeText(getApplicationContext(), "找不到語音裝置", 1).show();}}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stub//回調擷取從Google得到的資料 if(requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK){//取得語音的字元ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);String resultString="";for(int i=0;i<results.size();i++){resultString+=results.get(i);}Toast.makeText(this, resultString, 1).show();}super.onActivityResult(requestCode, resultCode, data);}}

           其主要原理就是將語音發送到google雲端,然後雲端處理,匹配相應的資料,發送到用戶端。

          最後不要忘記,在manifest中加入網路存取權限:

    

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

    

        運行後效果:

    

    點擊開始語音按鈕,然後開始說話(這裡要保證手機的網路是開啟的):

    

      正在等待雲端資料,由於我這是2G的卡,等了好長時間還是載入不下來,等回公司了用公司的wifi試試,如果得到雲端資料,就會通過Toast方式列印出來的。

      

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.