Android studio语音识别播报(科大讯飞)

准备

在科大讯飞官网下载Android MSC(SDK)

在下载好的SDK中把libs内的文件复制到工程的libs目录下

gson2.8.5下载链接:https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar

右键libs中的jar包,选择add as library

将SDK中的assets复制到main目录下

代码

MainActivity.java

package com.example.my_test_use;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
//所需申请的权限
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.INTERNET,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_NETWORK_STATE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA
};
public static class AudioUtils {
private static AudioUtils audioUtils;
private SpeechSynthesizer mySynthesizer;
public AudioUtils(){

}

public static AudioUtils getInstance() {
if (audioUtils == null) {
synchronized (AudioUtils.class) {
if (audioUtils == null) {
audioUtils = new AudioUtils();
}
}
}
return audioUtils;
}

private InitListener myInitListener = new InitListener() { @Override public void onInit(int code) { } };

public void init(Context context) {
mySynthesizer = SpeechSynthesizer.createSynthesizer(context, myInitListener);
mySynthesizer.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
//发音人xiaoyan
mySynthesizer.setParameter(SpeechConstant.SPEED,"50");
//语速50
mySynthesizer.setParameter(SpeechConstant.PITCH, "50");
//语调50
mySynthesizer.setParameter(SpeechConstant.VOLUME, "100");
//音量100
}

public void speakText(String content){
int code =mySynthesizer.startSpeaking(content,new SynthesizerListener(){

@Override
public void onSpeakBegin() {

}

@Override
public void onBufferProgress(int i, int i1, int i2, String s) {

}

@Override
public void onSpeakPaused() {

}

@Override
public void onSpeakResumed() {

}

@Override
public void onSpeakProgress(int i, int i1, int i2) {

}

@Override
public void onCompleted(SpeechError speechError) {

}

@Override
public void onEvent(int i, int i1, int i2, Bundle bundle) {

}
});
}
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applypermission();//申请app所需要用到的权限
// 将“xxxxxx”替换成您申请的APPID,申请地址:http://www.xfyun.cn
// 请勿在“=”与appid之间添加任何空字符或者转义符
SpeechUtility.createUtility(this, SpeechConstant.APPID +"=xxxxxx");
}

//定义判断权限申请的函数,在onCreat中调用就行
public void applypermission(){
if(Build.VERSION.SDK_INT>=23){
boolean needapply=false;
for(int i=0;i<PERMISSIONS_STORAGE.length;i++){
int chechpermission= ContextCompat.checkSelfPermission(getApplicationContext(),
PERMISSIONS_STORAGE[i]);
if(chechpermission!= PackageManager.PERMISSION_GRANTED){
needapply=true;
}
}
if(needapply){
ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS_STORAGE,1);
}
}
}
//重载用户是否同意权限的回调函数,进行相应处理
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for(int i=0;i<grantResults.length;i++){ //检查权限是否获取
if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
//同意后的操作
Toast.makeText(MainActivity.this, permissions[i]+"已授权",Toast.LENGTH_SHORT).show();//提示
}
else {
//不同意后的操作
Toast.makeText(MainActivity.this,permissions[i]+"拒绝授权",Toast.LENGTH_SHORT).show();//提示

}
}
}


public class use{
/**
*@TODO 科大讯飞语音听写
* linowl 2020.09.11
*/
public void initSpeech(final Context context) {
//1.创建RecognizerDialog对象
RecognizerDialog mDialog = new RecognizerDialog(context, null);
//识别器定义
final TextView txtdisplay = (TextView) findViewById(R.id.textview);
//定义局部变量txtdisplay TextView标签 id为textView
//2.设置accent、language等参数
mDialog.setParameter(SpeechConstant.DOMAIN,"iat");
//应用领域 iat:日常用语 medical:医疗
mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
//语言 zh_cn:中文 en_us:英文 ja_jp:日语 ko_kr:韩语 ru-ru:俄语 fr_fr:法语 es_es:西班牙语
mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
//方言 默认mandarin
//3.设置回调接口
mDialog.setListener(new RecognizerDialogListener() {
@Override
public void onResult(RecognizerResult recognizerResult, boolean isLast) {
if (!isLast) {
//解析语音
//返回的result为识别后的汉字,直接赋值到TextView上即可
String result = parseVoice(recognizerResult.getResultString());
// Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
txtdisplay.setText(result);
//识别成功在textView显示
}
}

@Override
public void onError(SpeechError speechError) {

}
});
//4.显示dialog,接收语音输入
mDialog.show();
}
}

/**
* 解析语音json
*/
public String parseVoice(String resultString) {
Gson gson = new Gson();
Voice voiceBean = gson.fromJson(resultString, Voice.class);

StringBuffer sb = new StringBuffer();
ArrayList<Voice.WSBean> ws = voiceBean.ws;
for (Voice.WSBean wsBean : ws) {
String word = wsBean.cw.get(0).w;
sb.append(word);
}
return sb.toString();
}
/**
* 语音实体类
*/
public class Voice {

public ArrayList<WSBean> ws;

public class WSBean {
public ArrayList<CWBean> cw;
}

public class CWBean {
public String w;
}
}

//调用use类的initSpeech函数
public void Recognition(View view){
new use().initSpeech(this);
}

public void broadcast(View view){
final EditText editext = (EditText) findViewById(R.id.edittext);
AudioUtils.getInstance().init(this); //初始化语音对象
AudioUtils.getInstance().speakText(editext.getText().toString()); //播放语音
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.216" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:onClick="Recognition"
android:text="识别"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textview" />

<EditText
android:id="@+id/edittext"
android:layout_width="323dp"
android:layout_height="68dp"
android:layout_marginTop="56dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:onClick="broadcast"
android:text="朗读"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edittext" />

</androidx.constraintlayout.widget.ConstraintLayout>

在AndroidManifest.xml添加权限

<!--连接网络权限,用于执行云端语音能力 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!--获取手机录音机使用权限,听写、识别、语义理解需要用到此权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!--读取网络信息状态 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--获取当前wifi状态 -->
<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.READ_CONTACTS"/>
<!--外存储写权限,构建语法需要用到此权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--外存储读权限,构建语法需要用到此权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<!--手机定位信息,用来为语义等功能提供定位,提供更精准的服务-->
<!--定位信息是敏感信息,可通过Setting.setLocationEnable(false)关闭定位请求 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--如需使用人脸识别,还要添加:摄相头权限,拍照需要用到 -->
<uses-permission android:name="android.permission.CAMERA" />

build.gradle

评论

  1. 2年前
    2020-9-12 14:21:20

    牛牛牛牛牛牛牛牛牛牛牛

  2. MJ
    已编辑
    2年前
    2020-9-13 14:49:39

    好棒哦,你好厉害,我好喜欢~~~ヾ(≧∇≦*)ゝ

  3. MJ
    2年前
    2020-9-15 8:55:18

    妙啊~

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇