Android 语音识别+语音搜索源码 Voice Search

http://blog.csdn.net/u014051380/article/details/21114389

 

1、判断是否已安装语音搜索功能

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.voice.search;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.util.List;  
  8. import android.app.Activity;  
  9. import android.app.AlertDialog;  
  10. import android.content.Context;  
  11. import android.content.DialogInterface;  
  12. import android.content.Intent;  
  13. import android.content.pm.PackageManager;  
  14. import android.content.pm.ResolveInfo;  
  15. import android.net.Uri;  
  16. import android.os.Environment;  
  17. import android.speech.RecognizerIntent;  
  18. import android.widget.Toast;  
  19.   
  20. public class VoiceSearchUtil {  
  21.   
  22.     private static Context context;  
  23.     private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;  
  24.   
  25.     public static void getVoiceSearch(Context c) {  
  26.         context = c;  
  27.         PackageManager pm = context.getPackageManager();  
  28.         List<ResolveInfo> activities = pm  
  29.                 .queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);  
  30.         if (activities.size() != 0) {  
  31.             /* 设备存在 */  
  32.             voiceSearch();  
  33.         } else {  
  34.             /* 没有设备请点击安装按钮进行安装呢 */  
  35.             if (copyApkFromAssets(context, "google_voice_search.apk", Environment.getExternalStorageDirectory()  
  36.                     .getAbsolutePath() + "/google_voice_search.apk")) {  
  37.                 new AlertDialog.Builder(context).setMessage("检测到未安装语音搜索设备,是否安装?")  
  38.                         .setPositiveButton("安装"new android.content.DialogInterface.OnClickListener() {  
  39.   
  40.                             @Override  
  41.                             public void onClick(DialogInterface dialog, int which) {  
  42.                                 Intent intent = new Intent(Intent.ACTION_VIEW);  
  43.                                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  44.                                 intent.setDataAndType(  
  45.                                         Uri.parse("file://"  
  46.                                             + Environment.getExternalStorageDirectory().getAbsolutePath()  
  47.                                                 + "/google_voice_search.apk"),  
  48.                                         "application/vnd.android.package-archive");  
  49.                                 context.startActivity(intent);  
  50.                             }  
  51.                         }).setNegativeButton("取消"null).show();  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     /** 
  57.      * 安装语音搜索功能,写入数据 
  58.      *  
  59.      * @param context 
  60.      *            上下文 
  61.      * @param fileName 
  62.      *            文件名称 
  63.      * @param path 
  64.      *            文件路径 
  65.      * @return 所需文件 
  66.      */  
  67.     public static boolean copyApkFromAssets(Context context, String fileName, String path) {  
  68.         boolean copyIsFinish = false;  
  69.         try {  
  70.             InputStream is = context.getAssets().open(fileName);  
  71.             File file = new File(path);  
  72.             file.createNewFile();  
  73.             FileOutputStream fos = new FileOutputStream(file);  
  74.             byte[] temp = new byte[1024];  
  75.             int i = 0;  
  76.             while ((i = is.read(temp)) > 0) {  
  77.                 fos.write(temp, 0, i);  
  78.             }  
  79.             fos.close();  
  80.             is.close();  
  81.             copyIsFinish = true;  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.         return copyIsFinish;  
  86.     }  
  87.   
  88.     // 语音搜索   
  89.     private static void voiceSearch() {  
  90.         try {  
  91.             // 通过Intent传递语音识别的模式,开启语音   
  92.             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
  93.             // 语言模式和自由模式的语音识别   
  94.             intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);  
  95.             // 提示语音开始   
  96.             intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");  
  97.             // 开始语音识别   
  98.             ((Activity) context).startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);  
  99.         } catch (Exception e) {  
  100.             e.printStackTrace();  
  101.             Toast.makeText(context, "找不到语音设备", Toast.LENGTH_LONG).show();  
  102.         }  
  103.     }  
  104.   
  105. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.voice.search;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.util.List;  
  8. import android.app.Activity;  
  9. import android.app.AlertDialog;  
  10. import android.content.Context;  
  11. import android.content.DialogInterface;  
  12. import android.content.Intent;  
  13. import android.content.pm.PackageManager;  
  14. import android.content.pm.ResolveInfo;  
  15. import android.net.Uri;  
  16. import android.os.Environment;  
  17. import android.speech.RecognizerIntent;  
  18. import android.widget.Toast;  
  19.   
  20. public class VoiceSearchUtil {  
  21.   
  22.     private static Context context;  
  23.     private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;  
  24.   
  25.     public static void getVoiceSearch(Context c) {  
  26.         context = c;  
  27.         PackageManager pm = context.getPackageManager();  
  28.         List<ResolveInfo> activities = pm  
  29.                 .queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);  
  30.         if (activities.size() != 0) {  
  31.             /* 设备存在 */  
  32.             voiceSearch();  
  33.         } else {  
  34.             /* 没有设备请点击安装按钮进行安装呢 */  
  35.             if (copyApkFromAssets(context, "google_voice_search.apk", Environment.getExternalStorageDirectory()  
  36.                     .getAbsolutePath() + "/google_voice_search.apk")) {  
  37.                 new AlertDialog.Builder(context).setMessage("检测到未安装语音搜索设备,是否安装?")  
  38.                         .setPositiveButton("安装"new android.content.DialogInterface.OnClickListener() {  
  39.   
  40.                             @Override  
  41.                             public void onClick(DialogInterface dialog, int which) {  
  42.                                 Intent intent = new Intent(Intent.ACTION_VIEW);  
  43.                                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  44.                                 intent.setDataAndType(  
  45.                                         Uri.parse("file://"  
  46.                                             + Environment.getExternalStorageDirectory().getAbsolutePath()  
  47.                                                 + "/google_voice_search.apk"),  
  48.                                         "application/vnd.android.package-archive");  
  49.                                 context.startActivity(intent);  
  50.                             }  
  51.                         }).setNegativeButton("取消"null).show();  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     /** 
  57.      * 安装语音搜索功能,写入数据 
  58.      *  
  59.      * @param context 
  60.      *            上下文 
  61.      * @param fileName 
  62.      *            文件名称 
  63.      * @param path 
  64.      *            文件路径 
  65.      * @return 所需文件 
  66.      */  
  67.     public static boolean copyApkFromAssets(Context context, String fileName, String path) {  
  68.         boolean copyIsFinish = false;  
  69.         try {  
  70.             InputStream is = context.getAssets().open(fileName);  
  71.             File file = new File(path);  
  72.             file.createNewFile();  
  73.             FileOutputStream fos = new FileOutputStream(file);  
  74.             byte[] temp = new byte[1024];  
  75.             int i = 0;  
  76.             while ((i = is.read(temp)) > 0) {  
  77.                 fos.write(temp, 0, i);  
  78.             }  
  79.             fos.close();  
  80.             is.close();  
  81.             copyIsFinish = true;  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.         return copyIsFinish;  
  86.     }  
  87.   
  88.     // 语音搜索  
  89.     private static void voiceSearch() {  
  90.         try {  
  91.             // 通过Intent传递语音识别的模式,开启语音  
  92.             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
  93.             // 语言模式和自由模式的语音识别  
  94.             intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);  
  95.             // 提示语音开始  
  96.             intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");  
  97.             // 开始语音识别  
  98.             ((Activity) context).startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);  
  99.         } catch (Exception e) {  
  100.             e.printStackTrace();  
  101.             Toast.makeText(context, "找不到语音设备", Toast.LENGTH_LONG).show();  
  102.         }  
  103.     }  
  104.   
  105. }  


2、assets提供语音搜索apk安装

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.voice.search;  
  2.   
  3. import java.util.ArrayList;  
  4. import android.os.Bundle;  
  5. import android.speech.RecognizerIntent;  
  6. import android.view.View;  
  7. import android.widget.Toast;  
  8. import android.app.Activity;  
  9. import android.app.AlertDialog;  
  10. import android.app.Dialog;  
  11. import android.content.Context;  
  12. import android.content.DialogInterface;  
  13. import android.content.Intent;  
  14.   
  15. public class MainActivity extends Activity {  
  16.   
  17.     private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;  
  18.     private String[] str;  
  19.     private Context context;  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         context = this;  
  26.     }  
  27.   
  28.     public void onClick(View v) {  
  29.         switch (v.getId()) {  
  30.         case R.id.search_iv:  
  31.             VoiceSearchUtil.getVoiceSearch(context);  
  32.             break;  
  33.         }  
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  38.         // 回调获取从谷歌得到的数据   
  39.         if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {  
  40.             // 取得语音的字符   
  41.             ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);  
  42.             // 循环所有结果存入数组   
  43.             str = new String[results.size()];  
  44.             for (int i = 0; i < results.size(); i++) { // 循环所有结果   
  45.                 str[i] = results.get(i);  
  46.             }  
  47.             // Dialog显示   
  48.             getSearchDialog();  
  49.             // 这里只获取第一条数据   
  50.             Toast.makeText(this, results.get(0), Toast.LENGTH_LONG).show();  
  51.         }  
  52.         super.onActivityResult(requestCode, resultCode, data);  
  53.     }  
  54.   
  55.     /*** 
  56.      * 搜索后dialog显示结果 
  57.      */  
  58.     private void getSearchDialog() {  
  59.         Dialog dialog = new AlertDialog.Builder(this).setTitle("你是不是想找:").setIcon(R.drawable.ic_launcher)  
  60.                 .setItems(str, new DialogInterface.OnClickListener() {  
  61.                     public void onClick(DialogInterface dialog, int which) {  
  62.                         Toast.makeText(MainActivity.this, str[which], Toast.LENGTH_SHORT).show();  
  63.                     }  
  64.                 }).setNegativeButton("取消"null).create();  
  65.         dialog.show();  
  66.     }  
  67.   
  68. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.voice.search;  
  2.   
  3. import java.util.ArrayList;  
  4. import android.os.Bundle;  
  5. import android.speech.RecognizerIntent;  
  6. import android.view.View;  
  7. import android.widget.Toast;  
  8. import android.app.Activity;  
  9. import android.app.AlertDialog;  
  10. import android.app.Dialog;  
  11. import android.content.Context;  
  12. import android.content.DialogInterface;  
  13. import android.content.Intent;  
  14.   
  15. public class MainActivity extends Activity {  
  16.   
  17.     private static final int VOICE_RECOGNITION_REQUEST_CODE = 1;  
  18.     private String[] str;  
  19.     private Context context;  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         context = this;  
  26.     }  
  27.   
  28.     public void onClick(View v) {  
  29.         switch (v.getId()) {  
  30.         case R.id.search_iv:  
  31.             VoiceSearchUtil.getVoiceSearch(context);  
  32.             break;  
  33.         }  
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  38.         // 回调获取从谷歌得到的数据  
  39.         if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {  
  40.             // 取得语音的字符  
  41.             ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);  
  42.             // 循环所有结果存入数组  
  43.             str = new String[results.size()];  
  44.             for (int i = 0; i < results.size(); i++) { // 循环所有结果  
  45.                 str[i] = results.get(i);  
  46.             }  
  47.             // Dialog显示  
  48.             getSearchDialog();  
  49.             // 这里只获取第一条数据  
  50.             Toast.makeText(this, results.get(0), Toast.LENGTH_LONG).show();  
  51.         }  
  52.         super.onActivityResult(requestCode, resultCode, data);  
  53.     }  
  54.   
  55.     /*** 
  56.      * 搜索后dialog显示结果 
  57.      */  
  58.     private void getSearchDialog() {  
  59.         Dialog dialog = new AlertDialog.Builder(this).setTitle("你是不是想找:").setIcon(R.drawable.ic_launcher)  
  60.                 .setItems(str, new DialogInterface.OnClickListener() {  
  61.                     public void onClick(DialogInterface dialog, int which) {  
  62.                         Toast.makeText(MainActivity.this, str[which], Toast.LENGTH_SHORT).show();  
  63.                     }  
  64.                 }).setNegativeButton("取消"null).create();  
  65.         dialog.show();  
  66.     }  
  67.   
  68. }  


3、加入Android读写文件权限

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值