Android TTS文字转语音开发

之前在做TTS开发的时候能够正常的将文字转为语音,但是今天做了一个小程序,结果却发不了音,仔细测试了一下,发现了一个问题。

首先先讲下TTS如何实现。

1、安装语音库,假如要中文发音,科大讯飞语音3.0就很好。

2、最简单的程序如下:

package com.example.tts;

import java.util.Locale;

import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{
	TextToSpeech textToSpeech = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textToSpeech = new TextToSpeech(this, this);			
		textToSpeech.speak("此处无声", TextToSpeech.QUEUE_ADD, null);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	protected void onDestroy()
    {    	
    	super.onDestroy();
    	if (textToSpeech!=null) {
    		textToSpeech.shutdown();
		}   		
    }
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			textToSpeech.speak("此处有声", TextToSpeech.QUEUE_FLUSH, null);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
		if (status == TextToSpeech.SUCCESS) {  
            int result = textToSpeech.setLanguage(Locale.CHINESE);          
            if (result == TextToSpeech.LANG_MISSING_DATA  
                    || result == TextToSpeech.LANG_NOT_SUPPORTED
                    || result == TextToSpeech.ERROR) {  
                Toast.makeText(this, "数据丢失或语言不支持", Toast.LENGTH_SHORT).show();  
            }  
            if (result == TextToSpeech.LANG_AVAILABLE) {
            	Toast.makeText(this, "支持该语言", Toast.LENGTH_SHORT).show();  
			}
            Toast.makeText(this, "初始化成功", Toast.LENGTH_SHORT).show();  
        } 
	}
}

无需任何权限,这里有个问题,就是在动态创建一个对象之后,在onCreate里面调用speak方法,并不能发出声音。

可以把文字保存为语音文件,也可以读取语音文件

	public void saveToFile(TextToSpeech speech,String text,String file)
	{		
		String destFileName = "/sdcard/tts/"+file+".wav";		
		speech.synthesizeToFile(text, null, destFileName);
	}
	
	public void readFromFile(TextToSpeech speech,String file)
	{
		String destFileName = "/sdcard/tts/"+file+".wav";
		speech.addSpeech("2", destFileName);		
		speech.speak("2", TextToSpeech.QUEUE_ADD, null);
		
	}

这样就可以了。

接下来讲一下如何实现语音识别

语音识别首先可以考虑使用科大讯飞,但是目前使用必须要联网,而且申请一个APPID。

用起来不难

1、语音合成功能

private SpeechSynthesizer speechSynthesizer;

SpeechUser.getUser().login(MainActivity.this, null, null, "appid=54d304cf", null);

speechSynthesizer = SpeechSynthesizer.createSynthesizer(this);
speechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
speechSynthesizer.setParameter(SpeechConstant.SPEED, "50");
speechSynthesizer.setParameter(SpeechConstant.VOLUME, "50");
speechSynthesizer.setParameter(SpeechConstant.PITCH, "50");

String text = editText.getText().toString();
speechSynthesizer.startSpeaking(text, null);

注册--设置--播放。文字转语音功能需要联网,但不需要正确的APPID,可以直接使用。但是语音识别就需要联网和正确的APPID


2、语音识别

private RecognizerDialog recognizerDialog;

SpeechUser.getUser().login(MainActivity.this, null, null, "appid=54d304cf", null);

recognizerDialog = new RecognizerDialog(this);
recognizerDialog.setParameter(SpeechConstant.DOMAIN, "iat");
recognizerDialog.setParameter(SpeechConstant.SAMPLE_RATE, "16000");

//显示Dialog
recognizerDialog.setListener(dialogListener);
recognizerDialog.show();

private RecognizerDialogListener dialogListener = new RecognizerDialogListener() {
//识别结果回调
@Override
public void onResult(RecognizerResult arg0, boolean arg1) {
// TODO Auto-generated method stub
String text = JsonParser.parseIatResult(arg0.getResultString());
editText.append(text);
editText.setSelection(editText.length());
}

//识别结束回调
@Override
public void onError(SpeechError arg0) {
// TODO Auto-generated method stub

}
};

package com.example.viocedemo;

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

import android.text.TextUtils;

/**
 * 对云端返回的Json结果进行解析
 * @author iFlytek
 * @since 20131211
 */
public class JsonParser {
	
	/**
	 * 听写结果的Json格式解析
	 * @param json
	 * @return
	 */
	public static String parseIatResult(String json) {
		if(TextUtils.isEmpty(json))
			return "";
		
		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"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
	
}

这样就可以实现语音输入了,非常简单。

你可能感兴趣的:(Android开发)