语音合成和识别接口

第一步:导入jar包
再libs文件夹,导入Msc.jar和Sunflower.jar,还有so包(这个要看手机是什么芯片)。

第二步:代码
MainActivity:

package com.example.speechtest2;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.thirdparty.t;


public class MainActivity extends ActionBarActivity
{
    //private static String TAG = TtsDemo.class.getSimpleName();

    private TextView hello;
    private Button btnButton;
    // 语音合成对象
    private SpeechSynthesizer mTts;

    // 默认发音人
    private String voicer = "xiaoyan";

    private String[] mCloudVoicersEntries;
    private String[] mCloudVoicersValue ;

    // 缓冲进度
    private int mPercentForBuffering = 0;
    // 播放进度
    private int mPercentForPlaying = 0;

    // 云端/本地单选按钮
    private RadioGroup mRadioGroup;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private Toast mToast;
    private SharedPreferences mSharedPreferences;

    public String xString = null;

    private SpeechRecognizer mIat;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hello = (TextView)findViewById(R.id.hello);
        btnButton = (Button)findViewById(R.id.btn);
        btnButton.setOnClickListener(t);
        //认证接口
        SpeechUtility.createUtility(getApplicationContext(), SpeechConstant.APPID+"=xxxx,usr=xxxx,pwd=xxxx");

        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(getApplicationContext(), null);
        //合成发音人
        mTts.setParameter(SpeechConstant.VOICE_NAME, "vixm"); 
        //设置合成返回音频的语速
        mTts.setParameter(SpeechConstant.SPEED, "50");
        //设置合成返回音频的音量
        mTts.setParameter(SpeechConstant.VOLUME, "80");
        //设置使用的引擎类型:在线、离线、混合。TYPE_CLOUD:云端引擎;TYPE_LOCAL:本地引擎;TYPE_MIX:混合引擎;
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        //设置路径
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/tts.wav");
        String text = "你好";
        //开始合成
        mTts.startSpeaking(text, mTtsListener);

        //语音识别
        mIat = SpeechRecognizer.createRecognizer(getApplicationContext(), null);
        //支持的应用领域,iat:短信和日常用语;video:视频;poi:地图; music:音乐
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        //语言区域,简体中文:zh_cn(默认);美式英文:en_us
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        //方言,普通话:mandarin(默认);粤 语:cantonese;四川话:lmz;河南话:henanese
        mIat.setParameter(SpeechConstant.ACCENT, "cantonese ");
        //开始录音
        mIat.startListening(mRecoListener);
    }

    private OnClickListener t =new OnClickListener(){

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            mIat.startListening(mRecoListener);
        }

    };

    //听写监听器
    private RecognizerListener mRecoListener = new RecognizerListener(){
    //听写结果回调接口(返回Json格式结果,用户可参见附录13.1);
    //一般情况下会通过onResults接口多次返回结果,完整的识别内容是多次结果的累加;
    //关于解析Json的代码可参见Demo中JsonParser类;
    //isLast等于true时会话结束。
    public void onResult(RecognizerResult results, boolean isLast) {
        Toast.makeText(getApplicationContext(), results.getResultString(), 500).show();
        xString = xString+results.getResultString();
        hello.setText(xString);
    }

    //会话发生错误回调接口
    public void onError(SpeechError error) {
    //打印错误码描述
    //Log.d(TAG, "error:" + error.getPlainDescription(true)); 
    }
    //开始录音
    public void onBeginOfSpeech() {}
    //volume音量值0~30, data音频数据
    public void onVolumeChanged(int volume, byte[] data){}
    //结束录音
    public void onEndOfSpeech() {}
    //扩展用接口
    public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {}

    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            showTip("开始播放");
        }

        @Override
        public void onSpeakPaused() {
            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                String info) {
            // 合成进度
            mPercentForBuffering = percent;
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                showTip("播放完成");
            } else if (error != null) {
                showTip(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
            // 若使用本地能力,会话id为null
            //  if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //      String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //      Log.d(TAG, "session id =" + sid);
            //  }
        }
    };

    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }
}

activity_main.xml

"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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.speechtest2.MainActivity" >

    "@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    

AndroidManifest.xml
把以下代码放在后面

    <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" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

语音识别返回的是json,如:

{"sn":1,"ls":false,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0.00,"w":"有"}],{"bg":0,"cw":[{"sc":0.00."w":"搞"}],{"bg":0,"cw":[{"sc":0.00,"w":"啊"}]}]}{"sn":2,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"sc":0.00,"w":"。"}]}]}

你可能感兴趣的:(android)