应用中添加讯飞语音功能

现在有很多应用都会有需求加入如果输入功能,在这里我就主要介绍讯飞语音

首先 :使用讯飞语音功能要到讯飞开放平台申请应用的app_id   http://open.voicecloud.cn/index.php/default/index

在我的语音云里点击创建先应用

创建完成后就可以得到应用的app_id


把app_id添加到应用中

 <string name="app_id">54575cec</string>
在讯飞语音中下载应用的sdk文件,这里我们只需要使用

把这五个添加到应用的libs的文件中


然后在应用中Build Path中添加Msc.jar



现在我们就可以在代码中添加语音功能的代码了

首先我们先自定义一个activity类

public abstract class PrentActicity extends Activity {

	protected Context context;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(LayoutId());
		this.context = this;
		
		SetContentView();
	}

	protected abstract int LayoutId();

	protected abstract void SetContentView();
然后继承这个类

public class PhoneManager extends PrentActicity {

	@Override
	protected int LayoutId() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	protected void SetContentView() {
		// TODO Auto-generated method stub
		
	}
}

在layoutid()中添加布局文件

这里xml文件我只添加一个edittext和一个button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/ed"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ok" />

</LinearLayout>


做完这样,我们就可以在我们之前定义的activity类中实现代码了

package com.example.demo;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint("SdCardPath")
public abstract class PrentActicity extends Activity {
	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog dialog;
	// 听写结果内容
	private EditText editText;
	private Toast toast;
	int ret = 0;
	private SharedPreferences sharedPreferences;
	protected Context context;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(LayoutId());
		this.context = this;
		// 初始化识别对象
		mIat = SpeechRecognizer.createRecognizer(context, mInitListener);
		// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
		dialog = new RecognizerDialog(context, mInitListener);
		sharedPreferences = getSharedPreferences("com.example.demo",Activity.MODE_PRIVATE);
		toast = toast.makeText(context, "", toast.LENGTH_SHORT);
		SetContentView();
	}

	protected abstract int LayoutId();

	protected abstract void SetContentView();
	/**
	 * 语音界面,只需要传入EditText即可showSpeechDialog(EditText);
	 */
	public void showSpeechDialog(EditText edit) 
	{
		this.editText = edit;
		// 设置参数
		setParam();
		boolean isShowDialog = sharedPreferences.getBoolean("iat_show", true);
		if (isShowDialog) 
		{
			// 显示听写对话框
			dialog.setListener(recognizerDialogListener);
			dialog.show();
			showTip("开始说话");
		} else 
		{
			showTip("听写失败");
		}

	}

	private InitListener mInitListener = new InitListener() 
	{
		@Override
		public void onInit(int arg0) {
			if (arg0 != ErrorCode.SUCCESS)
			{
				showTip("初始化失败,错误码:" + arg0);
			} else if (arg0 == 21001)
			{
				showTip("缺少讯飞组件,请下载讯飞语音+");
				dialog.dismiss();
			}

		}
	};

	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() 
	{

		@Override
		public void onResult(RecognizerResult arg0, boolean arg1) 
		{
			String text = JsonParser.parseIatResult(arg0.getResultString());
			editText.append(text);
			editText.setSelection(editText.length());
		}

		@Override
		public void onError(SpeechError arg0) 
		{
			showTip(arg0.getPlainDescription(true));
		}
	};


	private void showTip(final String str)
	{
		runOnUiThread(new Runnable() 
		{
			@Override
			public void run() 
			{
				toast.setText(str);
				toast.show();
			}
		});
	}

	public void setParam() 
	{
		String lag = sharedPreferences.getString("iat_language_preference",
				"mandarin");
		if (lag.equals("en_us")) 
		{
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else 
		{
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}
		// 设置语音前端点
		mIat.setParameter(SpeechConstant.VAD_BOS,sharedPreferences.getString("iat_vadbos_preference", "5000"));
		// 设置语音后端点
		mIat.setParameter(SpeechConstant.VAD_EOS,sharedPreferences.getString("iat_vadeos_preference", "1800"));
		// 设置标点符号
		mIat.setParameter(SpeechConstant.ASR_PTT,sharedPreferences.getString("iat_punc_preference", "1"));
		// 设置音频保存路径
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,"/sdcard/cryl/wavaudio.pcm");
	}

	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		// 退出时释放连接
		mIat.cancel();
		mIat.destroy();
	}

}
这样就可以在继承了该类的activity中使用了

package com.example.demo.ac;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.demo.PrentActicity;
import com.example.demo.R;

public class PhoneManager extends PrentActicity {

	EditText editText;
	Context context;

	@Override
	protected void SetContentView() {
		context = this;
		editText = (EditText) findViewById(R.id.ed);
		Button button = (Button) findViewById(R.id.btn);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showSpeechDialog(editText);
			}
		});
	}

	@Override
	protected int LayoutId() {
		return R.layout.phone_manager;
	}

}

由于讯飞语音使用的时候是联网操作,所以就需要进行数字解析

package com.example.demo;


import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Json结果解析类
 */
public class JsonParser {

	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"));
//				如果需要多候选结果,解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
	
	public static String parseGrammarResult(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");
				for(int j = 0; j < items.length(); j++)
				{
					JSONObject obj = items.getJSONObject(j);
					if(obj.getString("w").contains("nomatch"))
					{
						ret.append("没有匹配结果.");
						return ret.toString();
					}
					ret.append("【结果】" + obj.getString("w"));
					ret.append("【置信度】" + obj.getInt("sc"));
					ret.append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.append("没有匹配结果.");
		} 
		return ret.toString();
	}
}


使用语音输入时要application中添加该代码

package com.example.demo;

import com.iflytek.cloud.SpeechUtility;

public class Application extends android.app.Application{
	@Override
	public void onCreate() {
		SpeechUtility.createUtility(Application.this, "appid="+getString(R.string.app_id));
		super.onCreate();
	}
}

这里提醒一下,不要忘记添加相关的权限

<uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这里提供一个已经实现了语音功能的包 

下载地址  http://download.csdn.net/detail/u013255127/8118381

点击phonemanager按钮,就可以使用了



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值