回调接口和工具类(需要改成自己的appid)
import com.iflytek.cloud.RecognizerResult;
public interface XunFeiCallbackListener {
void onFinish(RecognizerResult results);
}
import android.content.Context;
import android.widget.Toast;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class XunFeiUtil {
public static String appid = "这里填写自己的appid";
public static void initXunFei(Context context){
SpeechUtility.createUtility(context, SpeechConstant.APPID +"="+appid);
}
public static void startVoice(Context context, final XunFeiCallbackListener callbackListener) {
RecognizerDialog dialog = new RecognizerDialog(context,null);
dialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
dialog.setParameter(SpeechConstant.ACCENT, "mandarin");
dialog.setParameter(SpeechConstant.ASR_PTT, "0");
dialog.setListener(new RecognizerDialogListener() {
@Override
public void onResult(RecognizerResult recognizerResult, boolean b) {
callbackListener.onFinish(recognizerResult);
}
@Override
public void onError(SpeechError speechError) {
}
});
dialog.show();
//Toast.makeText(this, "请开始说话", Toast.LENGTH_SHORT).show();
}
public static String parseIatResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
// 转写结果词,默认使用第一个结果
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
JSONObject obj = items.getJSONObject(0);
ret.append(obj.getString("w"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ret.toString();
}
}
MainActivity中的调用
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.iflytek.cloud.RecognizerResult;
import static net.guo.test.XunFeiUtil.parseIatResult;
import static net.guo.test.XunFeiUtil.*;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_click;
private EditText mResultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initXunFei(this);
btn_click = (Button) findViewById(R.id.btn_click);
mResultText = ((EditText) findViewById(R.id.result));
btn_click.setOnClickListener(this);
}
@Override
public void onClick(View v) {
startVoice(this, new XunFeiCallbackListener() {
@Override
public void onFinish(RecognizerResult results) {
String text = parseIatResult(results.getResultString());
// 自动填写地址
mResultText.append(text);
}
});
}
}
详细用法参见文档
运行结果