到了新公司,发现新公司的产品用到了语音提示,感觉很好玩,问了下,是用了讯飞语音,呵呵,前几天就下载相应的sdk包
整理下代码,以作记忆
import android.content.Context;
import android.os.RemoteException;
import android.util.Log;
import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.SpeechConstant;
import com.iflytek.speech.SpeechSynthesizer;
import com.iflytek.speech.SpeechUtility;
import com.iflytek.speech.SynthesizerListener;
/**
* 语音合成
*
* @author linchunda
*
*/
public class SpeakUtil {
private static String TAG = "SpeakUtil";
// 语音合成对象
private SpeechSynthesizer mTts;
private Context context;
private boolean ttsAvailable = false;// 语音合成是否可用
public SpeakUtil(Context context) {
this.context = context;
}
/**
* 初始化
*/
public void initSpeak() {
// 检测是否安装了讯飞语音服务
if (SpeechUtility.getUtility(context).queryAvailableEngines() == null
|| SpeechUtility.getUtility(context).queryAvailableEngines().length <= 0) {
// 下载安装或者本地安装,请参照demo代码
}
// 设置你申请的应用appid
SpeechUtility.getUtility(context).setAppid("应用appid");
// 初始化合成对象
mTts = new SpeechSynthesizer(context, mTtsInitListener);
}
/**
* 语音合成
*
* @param content
*/
public void speak(String content) {
// 参数设置
setParam();
// 语音合成
int code = mTts.startSpeaking(content, mTtsListener);
if (code != 0) {
Log.e(TAG, "start speak error : " + code);
} else {
Log.d(TAG, "start speak success.");
}
}
/**
* 初期化监听。
*/
private InitListener mTtsInitListener = new InitListener() {
@Override
public void onInit(ISpeechModule arg0, int code) {
Log.d(TAG, "InitListener init() code = " + code);
if (code == ErrorCode.SUCCESS) {
ttsAvailable = true;
}
}
};
/**
* 合成回调监听。
*/
private SynthesizerListener mTtsListener = new SynthesizerListener.Stub() {
@Override
public void onBufferProgress(int progress) throws RemoteException {
Log.d(TAG, "onBufferProgress :" + progress);
}
@Override
public void onCompleted(int code) throws RemoteException {
Log.d(TAG, "onCompleted code =" + code);
}
@Override
public void onSpeakBegin() throws RemoteException {
Log.d(TAG, "onSpeakBegin");
}
@Override
public void onSpeakPaused() throws RemoteException {
Log.d(TAG, "onSpeakPaused.");
}
@Override
public void onSpeakProgress(int progress) throws RemoteException {
Log.d(TAG, "onSpeakProgress :" + progress);
}
@Override
public void onSpeakResumed() throws RemoteException {
Log.d(TAG, "onSpeakResumed.");
}
};
/**
* 释放连接tts
*/
public void ttsDestroy() {
mTts.stopSpeaking(mTtsListener);
// 退出时释放连接
mTts.destory();
}
/**
* 参数设置
*
* @param param
* @return
*/
private void setParam() {
// 设置引擎类型
mTts.setParameter(SpeechConstant.ENGINE_TYPE, "local");
// 设置发音人
mTts.setParameter(SpeechSynthesizer.VOICE_NAME, "xiaoyan");
// 设置语速
mTts.setParameter(SpeechSynthesizer.SPEED, "50");
// 设置音调
mTts.setParameter(SpeechSynthesizer.PITCH, "50");
mTts.setParameter(SpeechSynthesizer.VOLUME, "80");
}
/**
* tts语音合成是否可用
*
* @return true为可用
*/
public boolean isTtsAvailable() {
return ttsAvailable;
}
}