“阿强,手写板怎么又不见了?”
最近,程序员阿强的那位勇于尝试新事物的外婆,又迷上了网购。在不太费劲儿地把购物软件摸得门儿清之后,没想到,本以为顺畅的网购之路,卡在了搜索物品上。
在手写输入环节,要么误操作,无意中更换到不熟悉的输入法;要么误按了界面上抽象的指令字符……于是阿强也经常收到外婆发来的求助。
其实,不止是购物应用,时下智能手机里装载的大部app,都是倾斜于年轻群体的交互设计,老年人想要体验学会使用,很难真香。
在一次次耐心指导外婆完成操作后,阿强,这个成熟coder给自己提了个需求:提升外婆的网购体验。不是一味让她适应输入法,而是让输入法迎合外婆的使用偏好习惯。
手动输入易出错,那就写个语音转文字的输入方法,只要启动录音按钮,实时语音识别输入,简单又快捷,外婆用了说直说好!
效果示例
应用场景
实时语音识别和音频转文字有着丰富的应用的场景。
游戏应用中的运用:当你在联机游戏场组队开黑时,通过实时语音识别跟队友无阻沟通,不占用双手的同时,也避免了开麦露出声音的尴尬。
办公应用中的运用:职场里,耗时长的会议,手打码字记录即低效,还容易漏掉细节,凭借音频文件转文字功能,转写会议讨论内容,会后对转写的文字进行梳理润色,事半功倍。
学习应用中的运用:时下越来越多的音频教学材料,一边观看一边暂停做笔记,很容易打断学习节奏,破坏学习过程的完整性,有了音频文件转写,系统的学习完教材后,再对文字进行复习梳理,学习体验更佳。
实现原理
华为机器学习服务提供实时语音识别和音频文件转写能力。
实时语音识别
支持将实时输入的短语音(时长不超过60秒)转换为文本,识别准确率可达95%以上。目前支持中文普通话、英语、中英混说、法语、德语、西班牙语、意大利语、阿拉伯语的识别。
- 支持实时出字。
- 提供拾音界面、无拾音界面两种方式。
- 支持端点检测,可准确定位开始和结束点。
- 支持静音检测,语音中未说话部分不发送语音包。
- 支持数字格式的智能转换,例如语音输入“二零二一年”时,能够智能识别为“2021年”。
音频文件转写
可将5小时内的音频文件转换成文字,支持输出标点符号,形成断句合理、易于理解的文本信息。同时支持生成带有时间戳的文本信息,便于后续进行更多功能开发。当前版本支持中英文的转写。
开发步骤
开发前准备
1. 配置华为maven仓地址并将agconnect-services.json文件放到app目录下:
打开android studio项目级“build.gradle”文件。
添加huawei agcp插件以及maven代码库。
- 在“allprojects > repositories”中配置hms core sdk的maven仓地址。
- 在“buildscript > repositories”中配置hms core sdk的maven仓地址。
- 如果app中添加了“agconnect-services.json”文件则需要在“buildscript > dependencies”中增加agcp配置。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
buildscript { repositories { google() jcenter() maven { url 'https://developer.huawei.com/repo/' } } dependencies { classpath 'com.android.tools.build:gradle:3.5.4' classpath 'com.huawei.agconnect:agcp:1.4.1.300' // note: do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() maven { url 'https://developer.huawei.com/repo/' } } } |
参见云端鉴权信息使用须知,设置应用的鉴权信息。
2. 添加编译sdk依赖:
1
2
3
4
5
6
7
8
9
10
|
dependencies { //音频文件转写能力 sdk implementation 'com.huawei.hms:ml-computer-voice-aft:2.2.0.300' // 实时语音转写 sdk. implementation 'com.huawei.hms:ml-computer-voice-asr:2.2.0.300' // 实时语音转写 plugin. implementation 'com.huawei.hms:ml-computer-voice-asr-plugin:2.2.0.300' ... } apply plugin: 'com.huawei.agconnect' // huawei agconnect gradle plugin |
3.在app的build中配置签名文件并将签名文件(xxx.jks)放入app目录下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
signingconfigs { release { storefile file( "xxx.jks" ) keyalias xxx keypassword xxxxxx storepassword xxxxxx v1signingenabled true v2signingenabled true } } buildtypes { release { minifyenabled false proguardfiles getdefaultproguardfile( 'proguard-android-optimize.txt' ), 'proguard-rules.pro' } debug { signingconfig signingconfigs.release debuggable true } } |
4.在manifest.xml中添加权限:
1
2
3
4
5
6
7
8
9
10
11
|
<uses-permission android:name= "android.permission.internet" /> <uses-permission android:name= "android.permission.read_external_storage" /> <uses-permission android:name= "android.permission.write_external_storage" /> <uses-permission android:name= "android.permission.access_network_state" /> <uses-permission android:name= "android.permission.access_wifi_state" /> <uses-permission android:name= "android.permission.record_audio" /> <application android:requestlegacyexternalstorage= "true" ... </application> |
接入实时语音识别能力
1.进行权限动态申请:
1
2
3
4
5
6
7
8
9
10
11
|
if (activitycompat.checkselfpermission( this , manifest.permission.record_audio) != packagemanager.permission_granted) { requestcamerapermission(); } private void requestcamerapermission() { final string[] permissions = new string[]{manifest.permission.record_audio}; if (!activitycompat.shouldshowrequestpermissionrationale( this , manifest.permission.record_audio)) { activitycompat.requestpermissions( this , permissions, constants.audio_permission_code); return ; } } |
2.创建intent,用于设置实时语音识别参数。
1
2
3
4
5
6
7
8
9
|
//设置您应用的鉴权信息 mlapplication.getinstance().setapikey(agconnectservicesconfig.fromcontext( this ).getstring( "client/api_key" )); 通过intent进行识别设置。 intent intentplugin = new intent( this , mlasrcaptureactivity. class ) // 设置识别语言为英语,若不设置,则默认识别英语。支持设置:"zh-cn":中文;"en-us":英语等。 .putextra(mlasrcaptureconstants.language, mlasrconstants.lan_zh_cn) // 设置拾音界面是否显示识别结果 .putextra(mlasrcaptureconstants.feature, mlasrcaptureconstants.feature_wordflux); startactivityforresult(intentplugin, "1" ); |
3.覆写“onactivityresult”方法,用于处理语音识别服务返回结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
@override protected void onactivityresult( int requestcode, int resultcode, @nullable intent data) { super .onactivityresult(requestcode, resultcode, data); string text = "" ; if ( null == data) { addtagitem( "intent data is null." , true ); } if (requestcode == "1" ) { if (data == null ) { return ; } bundle bundle = data.getextras(); if (bundle == null ) { return ; } switch (resultcode) { case mlasrcaptureconstants.asr_success: // 获取语音识别得到的文本信息。 if (bundle.containskey(mlasrcaptureconstants.asr_result)) { text = bundle.getstring(mlasrcaptureconstants.asr_result); } if (text == null || "" .equals(text)) { text = "result is null." ; log.e(tag, text); } else { //将语音识别结果设置在搜索框上 searchedit.settext(text); gosearch(text, true ); } break ; // 返回值为mlasrcaptureconstants.asr_failure表示识别失败。 case mlasrcaptureconstants.asr_failure: // 判断是否包含错误码。 if (bundle.containskey(mlasrcaptureconstants.asr_error_code)) { text = text + bundle.getint(mlasrcaptureconstants.asr_error_code); // 对错误码进行处理。 } // 判断是否包含错误信息。 if (bundle.containskey(mlasrcaptureconstants.asr_error_message)) { string errormsg = bundle.getstring(mlasrcaptureconstants.asr_error_message); // 对错误信息进行处理。 if (errormsg != null && ! "" .equals(errormsg)) { text = "[" + text + "]" + errormsg; } } //判断是否包含子错误码。 if (bundle.containskey(mlasrcaptureconstants.asr_sub_error_code)) { int suberrorcode = bundle.getint(mlasrcaptureconstants.asr_sub_error_code); // 对子错误码进行处理。 text = "[" + text + "]" + suberrorcode; } log.e(tag, text); break ; default : break ; } } } |
接入音频文件转写能力
1.申请动态权限。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
private static final int request_external_storage = 1 ; private static final string[] permissions_storage = { manifest.permission.read_external_storage, manifest.permission.write_external_storage }; public static void verifystoragepermissions(activity activity) { // check if we have write permission int permission = activitycompat.checkselfpermission(activity, manifest.permission.write_external_storage); if (permission != packagemanager.permission_granted) { // we don't have permission so prompt the user activitycompat.requestpermissions(activity, permissions_storage, request_external_storage); } } |
2.新建音频文件转写引擎并初始化;新建音频文件转写配置器。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// 设置 apikey. mlapplication.getinstance().setapikey(agconnectservicesconfig.fromcontext(getapplication()).getstring( "client/api_key" )); mlremoteaftsetting setting = new mlremoteaftsetting.factory() // 设置转写语言编码,使用bcp-47规范,当前支持中文普通话、英文转写。 .setlanguagecode( "zh" ) // 设置是否在转写输出的文本中自动增加标点符号,默认为false。 .enablepunctuation( true ) // 设置是否连带输出每段音频的文字转写结果和对应的音频时移,默认为false(此参数仅小于1分钟的音频需要设置)。 .enablewordtimeoffset( true ) // 设置是否输出句子出现在音频文件中的时间偏移值,默认为false。 .enablesentencetimeoffset( true ) .create(); // 新建音频文件转写引擎。 mlremoteaftengine engine = mlremoteaftengine.getinstance(); engine.init( this ); // 将侦听器回调传给第一步中定义的音频文件转写引擎中 engine.setaftlistener(aftlistener); |
3.新建侦听器回调,用于处理音频文件转写结果:
短语音转写:适用于时长小于1分钟的音频文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
private mlremoteaftlistener aftlistener = new mlremoteaftlistener() { public void onresult(string taskid, mlremoteaftresult result, object ext) { // 获取转写结果通知。 if (result.iscomplete()) { // 转写结果处理。 } } @override public void onerror(string taskid, int errorcode, string message) { // 转写错误回调函数。 } @override public void oninitcomplete(string taskid, object ext) { // 预留接口。 } @override public void onuploadprogress(string taskid, double progress, object ext) { // 预留接口。 } @override public void onevent(string taskid, int eventid, object ext) { // 预留接口。 } }; |
长语音转写:适用于时长大于1分钟的音频文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
private mlremoteaftlistener asrlistener = new mlremoteaftlistener() { @override public void oninitcomplete(string taskid, object ext) { log.e(tag, "mlasrcallback oninitcomplete" ); // 长语音初始化完成,开始转写 start(taskid); } @override public void onuploadprogress(string taskid, double progress, object ext) { log.e(tag, " mlasrcallback onuploadprogress" ); } @override public void onevent(string taskid, int eventid, object ext) { // 用于长语音 log.e(tag, "mlasrcallback onevent" + eventid); if (mlaftevents.uploaded_event == eventid) { // 文件上传成功 // 获取转写结果 startqueryresult(taskid); } } @override public void onresult(string taskid, mlremoteaftresult result, object ext) { log.e(tag, "mlasrcallback onresult taskid is :" + taskid + " " ); if (result != null ) { log.e(tag, "mlasrcallback onresult iscomplete: " + result.iscomplete()); if (result.iscomplete()) { timertask timertask = timertaskmap.get(taskid); if ( null != timertask) { timertask.cancel(); timertaskmap.remove(taskid); } if (result.gettext() != null ) { log.e(tag, taskid + " mlasrcallback onresult result is : " + result.gettext()); tvtext.settext(result.gettext()); } list<mlremoteaftresult.segment> words = result.getwords(); if (words != null && words.size() != 0 ) { for (mlremoteaftresult.segment word : words) { log.e(tag, "mlasrcallback word text is : " + word.gettext() + ", starttime is : " + word.getstarttime() + ". endtime is : " + word.getendtime()); } } list<mlremoteaftresult.segment> sentences = result.getsentences(); if (sentences != null && sentences.size() != 0 ) { for (mlremoteaftresult.segment sentence : sentences) { log.e(tag, "mlasrcallback sentence text is : " + sentence.gettext() + ", starttime is : " + sentence.getstarttime() + ". endtime is : " + sentence.getendtime()); } } } } } @override public void onerror(string taskid, int errorcode, string message) { log.i(tag, "mlasrcallback onerror : " + message + "errorcode, " + errorcode); switch (errorcode) { case mlafterrors.err_audio_file_notsupported: break ; } } }; // 上传转写任务 private void start(string taskid) { log.e(tag, "start" ); engine.setaftlistener(asrlistener); engine.starttask(taskid); } // 获取转写结果 private map<string, timertask> timertaskmap = new hashmap<>(); private void startqueryresult( final string taskid) { timer mtimer = new timer(); timertask mtimertask = new timertask() { @override public void run() { getresult(taskid); } }; // 10s轮训获取长语音转写结果 mtimer.schedule(mtimertask, 5000 , 10000 ); // 界面销毁前要清除 timertaskmap timertaskmap.put(taskid, mtimertask); } |
4.获取音频,上传音频文件到转写引擎中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
//获取音频文件的uri uri uri = getfileuri(); //获取音频时间 long audiotime = getaudiofiletimefromuri(uri); //判断音频时间是否超过60秒 if (audiotime < 60000 ) { // uri为从本地存储或者录音机读取到的语音资源,仅支持时长在1分钟之内的本地音频 this .taskid = this .engine.shortrecognize(uri, this .setting); log.i(tag, "short audio transcription." ); } else { // longrecognize为长语音转写接口,用于转写时长大于1分钟,小于5小时的语音。 this .taskid = this .engine.longrecognize(uri, this .setting); log.i(tag, "long audio transcription." ); } private long getaudiofiletimefromuri(uri uri) { long time = null ; cursor cursor = this .getcontentresolver() .query(uri, null , null , null , null ); if (cursor != null ) { cursor.movetofirst(); time = cursor.getlong(cursor.getcolumnindexorthrow(mediastore.video.media.duration)); } else { mediaplayer mediaplayer = new mediaplayer(); try { mediaplayer.setdatasource(string.valueof(uri)); mediaplayer.prepare(); } catch (ioexception e) { log.e(tag, "failed to read the file time." ); } time = long .valueof(mediaplayer.getduration()); } return time; } |
到此这篇关于300行代码让外婆实现语音搜索购物功能的文章就介绍到这了,更多相关外婆实现语音搜索购物内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://hmscore.blog.csdn.net/article/details/115242088