可以先看看我之前的博客:
Android studio调用科大讯飞的语音转文字功能
Android studio调用科大讯飞的关键词提取功能
Android studio根据文本提取出的关键词在sqlite数据库中查找相关内容
这篇博客主要是记录在Android studio上如何通过科大讯飞的SDK实现文字转语音功能。
1.首先需要在安卓中配置SDK以及相关权限等内容,由于之前语音转文字已经配置好了,所以不想要重新进行配置,配置方法可参考:
Android studio调用科大讯飞的语音转文字功能
2.新建Java类MyAPP,代码如下:
package com.example.myapplication;
import android.app.Application;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
public class MyAPP extends Application {
@Override
public void onCreate() {
super.onCreate();
SpeechUtility.createUtility(MyAPP.this, SpeechConstant.APPID + "=填写自己appid"); //初始化
}
}
3.新建Java类KqwSpeechCompound,代码如下:
package com.example.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
public class KqwSpeechCompound {
// Log标签
private static final String TAG = "KqwSpeechCompound";
// 上下文
private Context mContext;
// 语音合成对象
private static SpeechSynthesizer mTts;
/**
* 发音人
*/
public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹",
"小新", "楠楠", "老孙",};
public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei",
"xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils",};
/**
* 构造方法
*
* @param context
*/
public KqwSpeechCompound(Context context) {
Log.d("tag54", "初始化失败,错ss 误码:" );
// 上下文
mContext = context;
// 初始化合成对象
mTts = SpeechSynthesizer.createSynthesizer(mContext, new InitListener() {
@Override
public void onInit(int code) {
if (code != ErrorCode.SUCCESS) {
Log.d("tag54", "初始化失败,错误码:" + code);
}
Log.d("tag54", "初始化失败,q错误码:" + code);
}
});
}
/**
* 开始合成
*
* @param text
*/
public void speaking(String text) {
// 非空判断
if (TextUtils.isEmpty(text)) {
return;
}
int code = mTts.startSpeaking(text, mTtsListener);
Log.d("tag54","-----"+code+"++++++++++");
if (code != ErrorCode.SUCCESS) {
if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
Toast.makeText(mContext, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show();
}
}
}
/*
* 停止语音播报
*/
public static void stopSpeaking() {
// 对象非空并且正在说话
if (null != mTts && mTts.isSpeaking()) {
// 停止说话
mTts.stopSpeaking();
}
}
/**
* 判断当前有没有说话
*
* @return
*/
public static boolean isSpeaking() {
if (null != mTts) {
return mTts.isSpeaking();
} else {
return false;
}
}
/**
* 合成回调监听。
*/
private SynthesizerListener mTtsListener = new SynthesizerListener() {
@Override
public void onSpeakBegin() {
Log.i(TAG, "开始播放");
}
@Override
public void onSpeakPaused() {
Log.i(TAG, "暂停播放");
}
@Override
public void onSpeakResumed() {
Log.i(TAG, "继续播放");
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
// TODO 缓冲的进度
Log.i(TAG, "缓冲 : " + percent);
}
@Override
public void onSpeakProgress(int percent, int beginPos, int endPos) {
// TODO 说话的进度
Log.i(TAG, "合成 : " + percent);
}
@Override
public void onCompleted(SpeechError error) {
if (error == null) {
Log.i(TAG, "播放完成");
} else if (error != null) {
Log.i(TAG, error.getPlainDescription(true));
}
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
}
};
/**
* 参数设置
*
* @return
*/
private void setParam() {
// 清空参数
mTts.setParameter(SpeechConstant.PARAMS, null);
// 引擎类型 网络
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
// 设置发音人
mTts.setParameter(SpeechConstant.VOICE_NAME, COLOUD_VOICERS_VALUE[0]);
// 设置语速
mTts.setParameter(SpeechConstant.SPEED, "50");
// 设置音调
mTts.setParameter(SpeechConstant.PITCH, "50");
// 设置音量
mTts.setParameter(SpeechConstant.VOLUME, "100");
// 设置播放器音频流类型
mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
// mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/KRobot/wavaudio.pcm");
// 背景音乐 1有 0 无
// mTts.setParameter("bgs", "1");
}
}
4.在MainActivity.java中进行调用:
//合成语音
kqwSpeechCompound=new KqwSpeechCompound(this);
kqwSpeechCompound.speaking(resultcontent.trim());//resultcontent是一个字符串
综合之前的代码,MainActivity.java的全部代码如下:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.iflytek.cloud.RecognizerResult;
import static com.example.myapplication.XunFeiUtil.parseIatResult;
import static com.example.myapplication.XunFeiUtil.*;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_click;
private EditText mResultText;
private SQLiteDatabase readableDatabase;
private KqwSpeechCompound kqwSpeechCompound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//相当于建立连接
MySqlhelp mySqlhelp = new MySqlhelp(this,"database.db",null,1);
//打开 相当于数据库创建完成
readableDatabase = mySqlhelp.getReadableDatabase();
//创建things表
String sql = "create table if not exists things(name varchar(50) primary key ,content varchar(500))";
readableDatabase.execSQL(sql);
//插入几条数据
// sql = "insert into things values('水杯','水杯在客厅的桌子上')";
// readableDatabase.execSQL(sql);
// sql = "insert into things values('钥匙','钥匙在客厅的桌子上')";
// readableDatabase.execSQL(sql);
// sql = "insert into things values('鼠标','鼠标在卧室的桌子上')";
// readableDatabase.execSQL(sql);
//调用语音识别函数
initXunFei(this);
btn_click = (Button) findViewById(R.id.btn_click);
mResultText = ((EditText) findViewById(R.id.result));
//点击按钮进行识别
btn_click.setOnClickListener(this);
//合成语音
kqwSpeechCompound=new KqwSpeechCompound(this);
}
@Override
public void onClick(View v) {
startVoice(this, new XunFeiCallbackListener() {
@Override
public void onFinish(RecognizerResult results) {
String text = parseIatResult(results.getResultString());
// 获取语音转换成的文字
mResultText.append(text);
//调用python代码
initPython();// 初始化Python环境
Python py = Python.getInstance();
PyObject pyObject=py.getModule("tiquguanjianci").callAttr("main",text);
List returnList =pyObject.asList();//python代码返回的是list
int size = returnList.size();
String resultcontent="";//记录数据库查找结果
for (int i = 0; i < size; i++) {
String name= returnList.get(i).toString();//遍历每一个关键词
Log.d("res",name);
//查询数据库
String[] selectionArgs = new String[]{ name };
Cursor cursor = readableDatabase.query("things", null, "name=?", selectionArgs, null, null, null);
if (cursor!=null){
while (cursor.moveToNext()){
String content= cursor.getString(cursor.getColumnIndex("content"));//得到查询结果
resultcontent+=content;
}
cursor.close();
}
}
if(resultcontent=="")
{
resultcontent="抱歉,没有找到";
Log.d("res1","没有找到");
}
else
{
Log.d("res1",resultcontent);
}
kqwSpeechCompound.speaking(resultcontent.trim());
}
});
}
// 初始化Python环境
public void initPython(){
if (! Python.isStarted()) {
Python.start(new AndroidPlatform(this));
}
}
}