当前位置:   article > 正文

百度语音识别结合云知声离线TTSDemo(AS)_百度离线tts语音包

百度离线tts语音包

       最近项目需要,需要调研几家语音识别(离线/在线),语义理解,TTS(在线/离线),离线命令词,甚至百度的UNIT上下文使用等,虽然看的不怎么深入,但是也确实调研的不是,主要有百度,科大讯飞,搜狗,云知声,奇梦者等几家,还有包括硬件(科大的四麦直线麦克风,五麦环绕麦克风,最后升级的六麦环绕麦克风;奇梦者的四麦环绕麦克风+柱形麦克风阵列等)。也写了很多Demo,每一家的特色都不同。这里就不一一列举了。以后有机会在慢慢写下来,这里就简单给一个百度在线ASR和云知声离线TTS结合的案列,实现一个复读机的功能。

       因为现在比较晚了,我先上代码,后面会补充几点注意事项。

1,准备工作:

(1)百度SDK的JAR包bdasr_V3_xxx_xxx.jar与云知声的JAR包usc.jar:

百度SDK下载

云知声SDK下载

(先注册登录,选择服务再下载)

解压找到工程libs中的对应的jar(不在详说),添加在自己新建的工程的libs目录下,添加为library。

(2) so文件:同理,在刚刚下载的SDK中找到对应的so文件,然后早项目新建一个jniLibs目录(../src/main/)

(3)云知声离线TTS需要语音包(发不同音色使用的):使用时,需要先运行自己编写的工程,然后在对应设备的app安装的目录下新建tts文件夹,把下面三个文件放进去:

backend_female

backend_lzl

frontend_model

 

2,代码环节:

(1)AndroidManifest.xml:主要就是注意几个权限和百度的APP_ID,API_KEY,SECRET_KEY,这个需要自己创建应用,获取这三个值;这步不在累述。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="aoto.com.baidurecongdemo">
  4. <!-- begin: baidu speech sdk 权限 -->
  5. <uses-permission android:name="android.permission.RECORD_AUDIO" />
  6. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  7. <uses-permission android:name="android.permission.INTERNET" />
  8. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  9. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  10. <application
  11. android:allowBackup="true"
  12. android:icon="@mipmap/talk"
  13. android:label="@string/app_name"
  14. android:roundIcon="@mipmap/talk"
  15. android:supportsRtl="true"
  16. android:theme="@style/AppTheme">
  17. <activity android:name=".MainActivity">
  18. <intent-filter>
  19. <action android:name="android.intent.action.MAIN" />
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. <meta-data
  24. android:name="com.baidu.speech.APP_ID"
  25. android:value="XXXXXXX" />
  26. <meta-data
  27. android:name="com.baidu.speech.API_KEY"
  28. android:value="XXXXXXXXXXX..." />
  29. <meta-data
  30. android:name="com.baidu.speech.SECRET_KEY"
  31. android:value="XXXXXXXXXXXX...." />
  32. <service
  33. android:name=".ASRService"
  34. android:enabled="true"
  35. android:exported="true">
  36. <intent-filter>
  37. <action android:name="aoto.com.ASRService" />
  38. </intent-filter>
  39. </service>
  40. </application>
  41. </manifest>

 

(2)ASRService:这里我把百度语音识别写成了服务的形式,并开放了AIDL接口,别的应用可以直接调用即可(里面的方法未完善,学习者可以自行添加和修改)

  1. package aoto.com.baidurecongdemo;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.IBinder;
  5. import android.os.Message;
  6. import android.os.RemoteCallbackList;
  7. import android.os.RemoteException;
  8. import android.util.Log;
  9. import com.baidu.speech.EventListener;
  10. import com.baidu.speech.EventManager;
  11. import com.baidu.speech.EventManagerFactory;
  12. import com.baidu.speech.asr.SpeechConstant;
  13. import com.unisound.client.SpeechConstants;
  14. import com.unisound.client.SpeechSynthesizer;
  15. import com.unisound.client.SpeechSynthesizerListener;
  16. import org.json.JSONObject;
  17. import java.io.File;
  18. import java.util.LinkedHashMap;
  19. import java.util.Map;
  20. public class ASRService extends Service implements EventListener {
  21. private EventManager asr;
  22. public static String result;
  23. private boolean logTime = true;
  24. private String language;
  25. long startTime = 0;
  26. long endTime = 0;
  27. private MainActivity mainActivity = new MainActivity();
  28. private SpeechSynthesizer mTTSPlayer;
  29. private final String mFrontendModel= "/sdcard/unisound/tts/frontend_model";
  30. private final String mBackendModel = "/sdcard/unisound/tts/backend_lzl";
  31. //主动发数据
  32. final RemoteCallbackList<IRemoteServiceCallback> mCallbacks
  33. = new RemoteCallbackList<IRemoteServiceCallback>();
  34. private int mValue = 0;
  35. private static final int REPORT_MSG = 1;
  36. @Override
  37. public void onCreate() {
  38. System.out.println("服务创建了:" + "onCreate");
  39. asr = EventManagerFactory.create(this, "asr");
  40. asr.registerListener(this);
  41. super.onCreate();
  42. //初始化离线引擎
  43. initTts();
  44. }
  45. @Override
  46. public void onStart(Intent intent, int startId) {
  47. System.out.println("服务开启了:" + "onStart");
  48. super.onStart(intent, startId);
  49. }
  50. /**
  51. * 测试参数填在这里
  52. */
  53. public void start() {
  54. Map<String, Object> params = new LinkedHashMap<String, Object>();
  55. String event = null;
  56. event = SpeechConstant.ASR_START; // 替换成测试的event
  57. params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
  58. //判断调用者传过来的语言类型
  59. if (MainActivity.languge_id == 1) {
  60. params.put(SpeechConstant.PID, 1736);
  61. } else if (MainActivity.languge_id == 2) {
  62. params.put(SpeechConstant.PID, 1836);
  63. } else if (MainActivity.languge_id == 3) {
  64. params.put(SpeechConstant.PID, 1636);
  65. } else {
  66. params.put(SpeechConstant.PID, 1536);
  67. }
  68. System.out.println("MMMMMMMMMMMMMMMMMMLanguage:" + MainActivity.languge_id);
  69. // 请先使用如‘在线识别’界面测试和生成识别参数。 params同ActivityRecog类中myRecognizer.start(params);
  70. String json = null; //可以替换成自己的json
  71. json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
  72. asr.send(event, json, null, 0, 0);
  73. printLog("输入参数:" + json);
  74. }
  75. private void stop() {
  76. asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0); //
  77. }
  78. // EventListener 回调方法
  79. /**
  80. * @param name :当前asr状态
  81. * @param params :解析结果字符串
  82. * @author why
  83. */
  84. @Override
  85. public void onEvent(String name, String params, byte[] data, int offset, int length) {
  86. String logTxt = "name: " + name;
  87. if (params != null && !params.isEmpty()) {
  88. logTxt += " ;params :" + params;
  89. //通过name来确定当前状态,从而获取解析结果显示
  90. if (name.equals("asr.partial")) {
  91. String start = "[";
  92. String end = "]";
  93. //截取解析json字符串中结果显示
  94. result = StringTools.SubStringTwoChar(params, start, end);
  95. startTime = System.currentTimeMillis();
  96. }
  97. }
  98. if (name.equals("asr.finish")) {
  99. //识别结束
  100. if(MainActivity.btn.getText().toString().equals("停止")){
  101. if (result.equals("")||result==null){
  102. result="没有识别到声音";
  103. }
  104. MainActivity.btn.setText("开始");
  105. }
  106. else{
  107. if (result.equals("")||result==null){
  108. result="No sound at all";
  109. }
  110. MainActivity.btn.setText("start");
  111. }
  112. MainActivity.txtResult.setText(result);
  113. //TTS语音合成
  114. mTTSPlayer.playText(result);
  115. }
  116. //会话结束标识,发送广播传数据
  117. if (name.equals("asr.exit")) {
  118. mainActivity.test(result);
  119. }
  120. if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
  121. if (params.contains("\"nlu_result\"")) {
  122. if (length > 0 && data.length > 0) {
  123. logTxt += ", 语义解析结果:" + new String(data, offset, length);
  124. }
  125. }
  126. } else if (data != null) {
  127. logTxt += " ;data length=" + data.length;
  128. }
  129. //打印识别日志
  130. printLog(logTxt);
  131. }
  132. //打印识别日志实现
  133. private void printLog(String text) {
  134. if (logTime) {
  135. text += " ;time=" + System.currentTimeMillis();
  136. }
  137. text += "\n";
  138. Log.i(getClass().getName(), text);
  139. }
  140. //返回可调用服务方法的接口
  141. @Override
  142. public IBinder onBind(Intent intent) {
  143. System.out.println("MMMMMMMMMMMMMMMMM" + "服务绑定了!");
  144. return new MyASRresultAIDL();
  145. }
  146. //百度语音识别
  147. class MyASRresultAIDL extends ASRresultAIDL.Stub {
  148. @Override
  149. public String getASRResult() throws RemoteException {
  150. return result;
  151. }
  152. @Override
  153. public void callStart() throws RemoteException {
  154. start();
  155. }
  156. @Override
  157. public void callStop() throws RemoteException {
  158. stop();
  159. }
  160. }
  161. //初始化离线语音合成引擎实现
  162. private void initTts() {
  163. // 初始化语音合成对象
  164. //mTTSPlayer = new SpeechSynthesizer(this, Config.appKey, Config.secret);
  165. mTTSPlayer = new SpeechSynthesizer(this, "", "");
  166. System.out.println("TTTTTTTTTTTTTTTTTTS:"+mTTSPlayer);
  167. // 设置本地合成
  168. mTTSPlayer.setOption(SpeechConstants.TTS_SERVICE_MODE, SpeechConstants.TTS_SERVICE_MODE_LOCAL);
  169. File _FrontendModelFile = new File(mFrontendModel);
  170. if (!_FrontendModelFile.exists()) {
  171. System.out.println("文件:" + mFrontendModel + "不存在,请将assets下相关文件拷贝到SD卡指定目录!");
  172. }
  173. File _BackendModelFile = new File(mBackendModel);
  174. if (!_BackendModelFile.exists()) {
  175. System.out.println("文件:" + mBackendModel + "不存在,请将assets下相关文件拷贝到SD卡指定目录!");
  176. }
  177. // 设置前端模型
  178. mTTSPlayer.setOption(SpeechConstants.TTS_KEY_FRONTEND_MODEL_PATH, mFrontendModel);
  179. // 设置后端模型
  180. mTTSPlayer.setOption(SpeechConstants.TTS_KEY_BACKEND_MODEL_PATH, mBackendModel);
  181. // 设置回调监听
  182. mTTSPlayer.setTTSListener(new SpeechSynthesizerListener() {
  183. @Override
  184. public void onEvent(int type) {
  185. switch (type) {
  186. case SpeechConstants.TTS_EVENT_INIT:
  187. // 初始化成功回调
  188. Log.i("", "回调成功 ");
  189. break;
  190. case SpeechConstants.TTS_EVENT_SYNTHESIZER_START:
  191. // 开始合成回调
  192. Log.i("", "开始同步");
  193. break;
  194. case SpeechConstants.TTS_EVENT_SYNTHESIZER_END:
  195. // 合成结束回调
  196. Log.i("", "结束同步");
  197. break;
  198. case SpeechConstants.TTS_EVENT_BUFFER_BEGIN:
  199. // 开始缓存回调
  200. Log.i("", "开始缓存 ");
  201. break;
  202. case SpeechConstants.TTS_EVENT_BUFFER_READY:
  203. // 缓存完毕回调
  204. Log.i("", "准备缓存 ");
  205. break;
  206. case SpeechConstants.TTS_EVENT_PLAYING_START:
  207. // 开始播放回调
  208. Log.i("", "播放开始 ");
  209. break;
  210. case SpeechConstants.TTS_EVENT_PLAYING_END:
  211. // 播放完成回调
  212. Log.i("", "播放结束 ");
  213. break;
  214. case SpeechConstants.TTS_EVENT_PAUSE:
  215. // 暂停回调
  216. Log.i("", "暂停 ");
  217. break;
  218. case SpeechConstants.TTS_EVENT_RESUME:
  219. // 恢复回调
  220. //log_i("resume");
  221. break;
  222. case SpeechConstants.TTS_EVENT_STOP:
  223. // 停止回调
  224. Log.i("", "停止");
  225. break;
  226. case SpeechConstants.TTS_EVENT_RELEASE:
  227. // 释放资源回调
  228. Log.i("", "释放资源");
  229. break;
  230. default:
  231. break;
  232. }
  233. }
  234. @Override
  235. public void onError(int type, String errorMSG) {
  236. // 语音合成错误回调
  237. Log.e("","Error");
  238. }
  239. });
  240. // 初始化合成引擎
  241. int returnvalue= mTTSPlayer.init("");
  242. System.out.println("EEEEEEEEEEE:"+"初始化引擎"+returnvalue);
  243. }
  244. }

(3)StringUtils : ASRService中使用的一个工具类

  1. package aoto.com.baidurecongdemo;
  2. /**
  3. * author:why
  4. * created on: 2018/1/31 15:25
  5. * description:
  6. */
  7. public class StringTools {
  8. //截取固定字符床中指定两个字符或者字符串之间的子字符串
  9. /**
  10. *
  11. * @param target :要处理字符串
  12. * @param start :起始字符串/字符
  13. * @param end :结束字符串/字符
  14. * @return
  15. */
  16. public static String SubStringTwoChar(String target, String start, String end) {
  17. int startIndex = target.indexOf(start);
  18. int endIndex = target.indexOf(end);
  19. return target.substring(startIndex, endIndex).substring(start.length());
  20. }
  21. }

(4)MainActivity:调用服务,演示效果

  1. package aoto.com.baidurecongdemo;
  2. import android.Manifest;
  3. import android.content.ComponentName;
  4. import android.content.Intent;
  5. import android.content.ServiceConnection;
  6. import android.content.pm.PackageManager;
  7. import android.os.IBinder;
  8. import android.os.RemoteException;
  9. import android.support.v4.app.ActivityCompat;
  10. import android.support.v4.content.ContextCompat;
  11. import android.support.v7.app.AppCompatActivity;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.AbsSpinner;
  16. import android.widget.AdapterView;
  17. import android.widget.ArrayAdapter;
  18. import android.widget.Button;
  19. import android.widget.Spinner;
  20. import android.widget.TextView;
  21. import com.baidu.speech.asr.SpeechConstant;
  22. /**
  23. * @author why
  24. */
  25. public class MainActivity extends AppCompatActivity implements InterfaceTest{
  26. protected TextView txtLog;
  27. public static TextView txtResult;
  28. public static Button btn;
  29. private String result;
  30. private static String DESC_TEXT = "在线识别日志";
  31. public static int languge_id = 0;
  32. private Intent intent;
  33. private MyServiceConnection connection;
  34. private ASRresultAIDL asRresultAIDL;
  35. private Spinner spinner;
  36. private String butContext;
  37. /**
  38. * 测试参数填在这里
  39. */
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.common_mini);
  44. initView();
  45. intent = new Intent(this, ASRService.class);
  46. connection = new MyServiceConnection();
  47. bindService(intent, connection, BIND_AUTO_CREATE);
  48. }
  49. //触发语音识别开始与停止
  50. public void startOrEnd(View view) {
  51. butContext = btn.getText().toString();
  52. System.out.println("BBBBBBBBBBBBBBBBBBBBBB"+butContext);
  53. //先判断选择的语言
  54. if (butContext.equals("开始") || butContext.equals("start")) {
  55. //识别结果制空
  56. try {
  57. asRresultAIDL.callStart();
  58. } catch (RemoteException e) {
  59. e.printStackTrace();
  60. }
  61. if (butContext.equals("开始")) {
  62. ASRService.result="没有识别到声音";
  63. txtResult.setText("请说,我在听");
  64. btn.setText("停止");
  65. } else {
  66. ASRService.result="No sound at all";
  67. txtResult.setText("Please say,I am listening");
  68. btn.setText("stop");
  69. }
  70. } else {
  71. if (butContext.equals("停止")) {
  72. btn.setText("开始");
  73. try {
  74. txtResult.setText("识别结果:" + asRresultAIDL.getASRResult());
  75. } catch (RemoteException e) {
  76. e.printStackTrace();
  77. }
  78. } else {
  79. btn.setText("start");
  80. try {
  81. txtResult.setText("ASR result:" + asRresultAIDL.getASRResult());
  82. } catch (RemoteException e) {
  83. e.printStackTrace();
  84. }
  85. }
  86. try {
  87. asRresultAIDL.callStop();
  88. } catch (RemoteException e) {
  89. e.printStackTrace();
  90. }
  91. }
  92. }
  93. @Override
  94. protected void onDestroy() {
  95. unbindService(connection);
  96. super.onDestroy();
  97. }
  98. private void initView() {
  99. txtResult = (TextView) findViewById(R.id.txtResult);
  100. txtLog = (TextView) findViewById(R.id.txtLog);
  101. btn = (Button) findViewById(R.id.btn);
  102. txtLog.setText(DESC_TEXT + "\n");
  103. spinner = findViewById(R.id.languge_list);
  104. //下拉框实现
  105. ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Data, android.R.layout.simple_spinner_item);
  106. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  107. spinner.setAdapter(adapter);
  108. spinner.setPrompt("选择语言");
  109. //设置下拉框监听
  110. spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  111. @Override
  112. public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  113. languge_id = position;
  114. System.out.println("QQQQQQQQQQQQQQQQQQQQQ"+languge_id);
  115. switch (languge_id) {
  116. //普通话
  117. case 0:
  118. txtResult.setText("点击‘开始’");
  119. btn.setText("开始");
  120. break;
  121. //英语
  122. case 1:
  123. //interfaceBaiduParams.setLanguage("English");
  124. txtResult.setText("click 'start'");
  125. btn.setText("start");
  126. break;
  127. // 四川话
  128. case 2:
  129. //interfaceBaiduParams.setLanguage("SiChuanHua");
  130. txtResult.setText("点击‘开始’");
  131. btn.setText("开始");
  132. break;
  133. //粤语
  134. case 3:
  135. //interfaceBaiduParams.setLanguage("YueYu");
  136. txtResult.setText("点击‘开始’");
  137. btn.setText("开始");
  138. break;
  139. }
  140. }
  141. @Override
  142. public void onNothingSelected(AdapterView<?> parent) {
  143. }
  144. });
  145. }
  146. @Override
  147. public void test(String str) {
  148. }
  149. private class MyServiceConnection implements ServiceConnection {
  150. @Override
  151. public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  152. asRresultAIDL = ASRresultAIDL.Stub.asInterface(iBinder);
  153. System.out.println("绑定服务成功了");
  154. }
  155. @Override
  156. public void onServiceDisconnected(ComponentName componentName) {
  157. System.out.println("解绑服务成功了");
  158. }
  159. }
  160. }

(5)ASRresultAIDL.aidl:开放服务里面的方法,供其他应用调用

  1. // ASRresultAIDL.aidl
  2. package aoto.com.baidurecongdemo;
  3. // Declare any non-default types here with import statements
  4. interface ASRresultAIDL {
  5. String getASRResult();
  6. void callStart();
  7. void callStop();
  8. }

(6)build.gradle:

  1. apply plugin: 'com.android.application'
  2. android {
  3. compileSdkVersion 26
  4. defaultConfig {
  5. applicationId "aoto.com.baidurecongdemo"
  6. minSdkVersion 21
  7. targetSdkVersion 26
  8. versionCode 1
  9. versionName "1.0"
  10. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  11. //加载对应so文件
  12. ndk{
  13. abiFilters 'armeabi'
  14. }
  15. }
  16. buildTypes {
  17. release {
  18. minifyEnabled false
  19. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  20. }
  21. }
  22. }
  23. dependencies {
  24. implementation fileTree(include: ['*.jar'], dir: 'libs')
  25. implementation 'com.android.support:appcompat-v7:26.1.0'
  26. implementation 'com.android.support.constraint:constraint-layout:1.0.2'
  27. testImplementation 'junit:junit:4.12'
  28. androidTestImplementation 'com.android.support.test:runner:1.0.1'
  29. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
  30. implementation files('libs/bdasr_V3_20171108_9800a2a.jar')
  31. implementation files('libs/usc.jar')
  32. }

3,注意事项:

(1)云知声离线TTSso文件不是X86的,所以window下的x86模拟器是用不了的,但是在window系统下运行arm的模拟器很卡,所以建议真机调试

(2)我这里在百度语音识别的地方只是实现了最简单的语音识别调用流程,很多的参数没有使用,学习者可以自己完善和添加

(3)我这里只添加了百度armeabi下的so文件,所以在gradle文件用ndk指定了(ndk已经安装),也可以什么都不加

(4)我这里主要是实现了一个复读机的功能,你说什么,那边会把识别文本语音合成播放出来,可以自己选择音色

(5)我这里百度开发了四种语言语音识别

注:欢迎扫码关注

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/471667
推荐阅读
相关标签
  

闽ICP备14008679号