科大讯飞的语音识别功能用在安卓代码中,我把语音识别写成了Service,然后在Fragment直接调用service服务。科大讯飞语音识别用的是带对话框的那个,直接调用科大讯飞的语音接口,代码采用链表结果集的方式获取数据。
这个语音识别需要在官网申请APPID
本博来自:http://blog.csdn.net/zhaocundang 小波LinuxQQ463431476
测试:
自己项目采用了科大讯飞语音识别服务,报告中是这样解释的:
语音Service服务代码设计
(1)要想写好Service代码,必须了解Service的生命周期.
(2)首先启动Service服务的方法是:
getActivity().startService(new Intent(getActivity(),VoiceService.class));
停止Service服务:
getActivity().stopService(new Intent(getActivity(),VoiceService.class));
(3)将类继承与Service:
public class VoiceService extends Service{
}
自动重载OnBind()函数,通过OnBind()的返回值,将Service的实例返回调用者。
(3) 调用科大讯飞语音API接口代码
先调用手机麦克风录音:
rd.setSampleRate(RATE.rate16k);
调用语音API包中的语音识别对话框,将录音发送到服务器,并接受服务器返回的结果,将数据以链表数据结构的形式传过来,获取结果:
final StringBuilder sb = new StringBuilder();
rd.setListener(new RecognizerDialogListener() {
public void onResults(ArrayList result, boolean isLast) {
for (RecognizerResult recognizerResult : result) {
sb.append(recognizerResult.text);
}
}
public void onEnd(SpeechError error) {
}
});
(4)文本语音朗读的调用:
先是声明播放对象:
private static SynthesizerPlayer player ;
这里我直接封装一个朗读函数,appid是申请的应用授权id,代码如下:
public void speak(String words){
player = SynthesizerPlayer.createSynthesizerPlayer(getActivity(),”appid=57527406”);
player.playText(words, null,null); //播放文本
}
主要的代码:
开启和关闭服务:
public void onClick(View v) {
服务中:
package zcd.voice; import java.util.ArrayList; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.view.WindowManager; import android.widget.Toast; import com.iflytek.speech.RecognizerResult; import com.iflytek.speech.SpeechConfig.RATE; import com.iflytek.speech.SpeechError; import com.iflytek.ui.RecognizerDialog; import com.iflytek.ui.RecognizerDialogListener; public class VoiceService extends Service{ private RecognizerDialog rd; private String text; @Override public IBinder onBind(Intent intent) {