1. 程式人生 > >語音合成和識別介面

語音合成和識別介面

第一步:匯入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

<RelativeLayout 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: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" >

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="重新再講"
        android:layout_below="@+id/hello"
        />

</RelativeLayout>

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":"。"}]}]}