帮助文档:https://cloud.tencent.com/document/product/1093/38351
开发准备
SDK 下载
录音文件识别 Android SDK 及 Demo 下载地址:Android SDK
F:code_demo_androidasrQCloudOneSentenceSDK_AndroidQCloudOneSentenceSDK_badam_v2.0.1srcQCloudSDKOneSentenceDemo
第一步,打开项目
第二步,解决遇到的错误
解决办法
添加依赖
在Dependencies中更新扩展,选中app(当前项目),查看当前app下所有扩展,是否需要更新(波浪线代表需要更新版本),点击Update进行更新,无则不更新.
设置项目秘钥配置 DemoConfig.java
目录的路径
QCloudSDKOneSentenceDemo/app/src/main/java/com/tencent/cloud/qcloudsdkonesentencedemo/DemoConfig.java
开发前
- 开发者使用录音文件识别功能前,需要先在 腾讯云控制台 注册账号, 并获得 APPID、SecretId 和 SecretKey 信息。
- 手机必须要有网络(GPRS、3G 或 Wi-Fi 等)。
- 支持 Android 4.0 及其以上版本。
运行环境配置
添加录音文件识别 SDK aar
将 qcloudasrsdk_2.0_release.aar 放在 libs 目录下,在 App 的 build.gradle 文件中添加。
代码语言:txt复制implementation(name: 'qcloudasrsdk_2.0_release', ext: 'aar')
添加其他依赖,在 App 的 build.gradle 文件中添加。
代码语言:txt复制 implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:okhttp:4.0.0-RC1'
implementation 'com.squareup.okio:okio:1.11.0'
implementation 'org.slf4j:slf4j-api:1.7.25'
添加之后
在 AndroidManifest.xml 添加如下权限:
代码语言:txt复制< uses-permission android:name="android.permission.RECORD_AUDIO"/>
< uses-permission android:name="android.permission.INTERNET"/>
< uses-permission android:name="android.permission.WRITE_SETTINGS" />
< uses-permission android:name="android.permission.READ_PHONE_STATE"/>
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
< uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
添加之后是报错的
看一下这个报错是怎么解决的呢,这个只要把尖括号前面的空格去掉就可以了。
录音文件识别的代码
代码语言:javascript复制package com.tencent.cloud.qcloudsdkonesentencedemo;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.tencent.cloud.qcloudasrsdk.common.QCloudSourceType;
import com.tencent.cloud.qcloudasrsdk.models.QCloudFileRecognitionParams;
import com.tencent.cloud.qcloudasrsdk.recognizer.QCloudFileRecognizer;
import com.tencent.cloud.qcloudasrsdk.recognizer.QCloudFileRecognizerListener;
import com.victor.loading.rotate.RotateLoading;
import java.io.IOException;
import java.io.InputStream;
public class FileRecognizeActivity extends AppCompatActivity implements QCloudFileRecognizerListener {
private boolean recording = false;
private QCloudFileRecognizer fileRecognizer;
private int REQUEST_CODE = 1002;
//磁盘读写权限 麦克风录音权限
String[] permiss = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO};
private void showLoading(boolean showLoading) {
RotateLoading rotateLoading = findViewById(R.id.rotateloading);
if (showLoading) {
rotateLoading.start();
}
else {
rotateLoading.stop();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_file_sentence_recognize);
RotateLoading rotateLoading = findViewById(R.id.rotateloading);
rotateLoading.setLoadingColor(Color.parseColor("#FF79CD6E"));
if(!checkMyPermission(permiss)){
ActivityCompat.requestPermissions(this,permiss, REQUEST_CODE);
}
if (fileRecognizer == null) {
fileRecognizer = new QCloudFileRecognizer(DemoConfig.apppId, DemoConfig.secretId, DemoConfig.secretKey);
fileRecognizer.setCallback(this);
}
System.out.println(Thread.currentThread());
findViewById(R.id.recognize_ur_btn).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
showLoading(true);
QCloudFileRecognitionParams params = (QCloudFileRecognitionParams) QCloudFileRecognitionParams.defaultRequestParams();
params.setUrl("http://client-sdk-1255628450.cossh.myzijiebao.com/test audio/voice_WGVNG_8000.mp3");
params.setSourceType(QCloudSourceType.QCloudSourceTypeUrl);
params.setFilterDirty(0);// 0 :默认状态 不过滤脏话 1:过滤脏话
params.setFilterModal(0);// 0 :默认状态 不过滤语气词 1:过滤部分语气词 2:严格过滤
params.setConvertNumMode(1);//1:默认状态 根据场景智能转换为阿拉伯数字;0:全部转为中文数字。
// params.setHotwordId(""); // 热词id。用于调用对应的热词表,如果在调用语音识别服务时,不进行单独的热词id设置,自动生效默认热词;如果进行了单独的热词id设置,那么将生效单独设置的热词id。
fileRecognizer.recognize(params);
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception msg" e.getMessage());
} finally {
}
}
});
findViewById(R.id.recognize_ur_data).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputStream is = null;
try {
showLoading(true);
AssetManager am = getResources().getAssets();
is = am.open("test1.mp3");
int length = is.available();
byte[] audioData = new byte[length];
is.read(audioData);
QCloudFileRecognitionParams params = (QCloudFileRecognitionParams) QCloudFileRecognitionParams.defaultRequestParams();
params.setData(audioData);
params.setSourceType(QCloudSourceType.QCloudSourceTypeData);
params.setFilterDirty(0);// 0 :默认状态 不过滤脏话 1:过滤脏话
params.setFilterModal(0);// 0 :默认状态 不过滤语气词 1:过滤部分语气词 2:严格过滤
params.setConvertNumMode(1);//1:默认状态 根据场景智能转换为阿拉伯数字;0:全部转为中文数字。
// params.setHotwordId("");
fileRecognizer.recognize(params);
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("exception msg" e.getMessage());
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void updateUI() {
Button recordButton = findViewById(R.id.recognize_start_record);
if (recording) {
recordButton.setText("stopRecord");
}
else {
recordButton.setText("startRecord");
}
}
private boolean checkMyPermission(String[] permiss){
if(permiss !=null && permiss.length > 0 ){
for(String per : permiss) {
if (ContextCompat.checkSelfPermission(this, per) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
if (requestCode == REQUEST_CODE) {
boolean isAllGranted = true;
// 判断是否所有的权限都已经授予了
for (int grant : grantResults) {
if (grant != PackageManager.PERMISSION_GRANTED) {
isAllGranted = false;
break;
}
}
if (isAllGranted) {
} else {
// 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
openAppDetails();
}
}
}
/**
* 打开 APP 的详情设置
*/
private void openAppDetails() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("录音需要访问 “外部存储器”,请到 “应用信息 -> 权限” 中授予!");
builder.setPositiveButton("去手动授权", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
@Override
protected void onStart() {
super.onStart();
}
/*录音文件识别结果回调*/
@Override
public void recognizeResult(QCloudFileRecognizer recognizer, final long requestId, String result,int status, Exception exception) {
if(status==2||status==3){
showLoading(false);
}
TextView textView = findViewById(R.id.recognize_text_view);
Log.e("recognizeResult","thread id:" Thread.currentThread().getId() " name:" Thread.currentThread().getName());
if (exception != null) {
Log.e("recognizeResult","result: " result "exception msg" exception exception.getLocalizedMessage());
textView.setText(exception.getLocalizedMessage());
showLoading(false);
}
else {
Log.e("recognizeResult","result: " result "---status==" status);
if(!TextUtils.isEmpty(result)){
String pattern = "\[[^\]] \]"; //中括号内
// String pattern = "\([^)]*\)";//括号内
//String pattern = "\(. "
result = result.replaceAll(pattern, "");
}
textView.setText(result);
}
}
}