音频录音文件实现语音转换识别文字最后文档输出结果
实现对mp3等录音文件进行语音识别成文字,最终获取文档格式或者其它定义格式文件,也可以进行提取数据处理逻辑,轻松实现大文件的语音文字转换功能,精准高效便捷...
功能技术:java+阿里云语音识别+OSS文件存储
*注意:文件需要有读写和可下载访问权限
代码实现
配置地域ID、常量、固定值:
// 地域ID,常量,固定值。(根据自己开通地址配置)public static final String REGIONID = "cn-shenzhen";public static final String ENDPOINTNAME = "cn-shenzhen";public static final String PRODUCT = "nls-filetrans";public static final String DOMAIN = "filetrans.cn-shenzhen.aliyuncs.com";public static final String API_VERSION = "2018-08-17"; // 中国站版本// public static final String API_VERSION = "2019-08-23"; // 国际站版本public static final String POST_REQUEST_ACTION = "SubmitTask";public static final String GET_REQUEST_ACTION = "GetTaskResult";// 请求参数public static final String KEY_APP_KEY = "appkey";public static final String KEY_FILE_LINK = "file_link";public static final String KEY_VERSION = "version";public static final String KEY_ENABLE_WORDS = "enable_words";// 响应参数public static final String KEY_TASK = "Task";public static final String KEY_TASK_ID = "TaskId";public static final String KEY_STATUS_TEXT = "StatusText";public static final String KEY_RESULT = "Result";// 状态值public static final String STATUS_SUCCESS = "SUCCESS";private static final String STATUS_RUNNING = "RUNNING";private static final String STATUS_QUEUEING = "QUEUEING";
完整代码:
package com.jame.excel.excelManager;import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;import java.io.File;
import java.util.ArrayList;
import java.util.List;public class FileTransJavaDemo {// 地域ID,常量,固定值。public static final String REGIONID = "cn-shenzhen";public static final String ENDPOINTNAME = "cn-shenzhen";public static final String PRODUCT = "nls-filetrans";public static final String DOMAIN = "filetrans.cn-shenzhen.aliyuncs.com";public static final String API_VERSION = "2018-08-17"; // 中国站版本// public static final String API_VERSION = "2019-08-23"; // 国际站版本public static final String POST_REQUEST_ACTION = "SubmitTask";public static final String GET_REQUEST_ACTION = "GetTaskResult";// 请求参数public static final String KEY_APP_KEY = "appkey";public static final String KEY_FILE_LINK = "file_link";public static final String KEY_VERSION = "version";public static final String KEY_ENABLE_WORDS = "enable_words";// 响应参数public static final String KEY_TASK = "Task";public static final String KEY_TASK_ID = "TaskId";public static final String KEY_STATUS_TEXT = "StatusText";public static final String KEY_RESULT = "Result";// 状态值public static final String STATUS_SUCCESS = "SUCCESS";private static final String STATUS_RUNNING = "RUNNING";private static final String STATUS_QUEUEING = "QUEUEING";// 阿里云鉴权clientIAcsClient client;public FileTransJavaDemo(String accessKeyId, String accessKeySecret) {// 设置endpointtry {DefaultProfile.addEndpoint(ENDPOINTNAME, REGIONID, PRODUCT, DOMAIN);} catch (ClientException e) {e.printStackTrace();}// 创建DefaultAcsClient实例并初始化DefaultProfile profile = DefaultProfile.getProfile(REGIONID, accessKeyId, accessKeySecret);this.client = new DefaultAcsClient(profile);}public String submitFileTransRequest(String appKey, String fileLink) {/*** 1. 创建CommonRequest,设置请求参数。*/CommonRequest postRequest = new CommonRequest();// 设置域名postRequest.setDomain(DOMAIN);// 设置API的版本号,格式为YYYY-MM-DD。postRequest.setVersion(API_VERSION);// 设置actionpostRequest.setAction(POST_REQUEST_ACTION);// 设置产品名称postRequest.setProduct(PRODUCT);/*** 2. 设置录音文件识别请求参数,以JSON字符串的格式设置到请求Body中。*/JSONObject taskObject = new JSONObject();// 设置appkeytaskObject.put(KEY_APP_KEY, appKey);// 设置音频文件访问链接taskObject.put(KEY_FILE_LINK, fileLink);// 新接入请使用4.0版本,已接入(默认2.0)如需维持现状,请注释掉该参数设置。taskObject.put(KEY_VERSION, "4.0");// 设置是否输出词信息,默认为false,开启时需要设置version为4.0及以上。taskObject.put(KEY_ENABLE_WORDS, true);taskObject.put("enable_sample_rate_adaptive", true);String task = taskObject.toJSONString();System.out.println(task);// 设置以上JSON字符串为Body参数。postRequest.putBodyParameter(KEY_TASK, task);// 设置为POST方式的请求。postRequest.setMethod(MethodType.POST);/*** 3. 提交录音文件识别请求,获取录音文件识别请求任务的ID,以供识别结果查询使用。*/String taskId = null;try {CommonResponse postResponse = client.getCommonResponse(postRequest);System.err.println("提交录音文件识别请求的响应:" + postResponse.getData());if (postResponse.getHttpStatus() == 200) {JSONObject result = JSONObject.parseObject(postResponse.getData());String statusText = result.getString(KEY_STATUS_TEXT);if (STATUS_SUCCESS.equals(statusText)) {taskId = result.getString(KEY_TASK_ID);}}} catch (ClientException e) {e.printStackTrace();}return taskId;}public String getFileTransResult(String taskId) {/*** 1. 创建CommonRequest,设置任务ID。*/CommonRequest getRequest = new CommonRequest();// 设置域名getRequest.setDomain(DOMAIN);// 设置API版本getRequest.setVersion(API_VERSION);// 设置actiongetRequest.setAction(GET_REQUEST_ACTION);// 设置产品名称getRequest.setProduct(PRODUCT);// 设置任务ID为查询参数getRequest.putQueryParameter(KEY_TASK_ID, taskId);// 设置为GET方式的请求getRequest.setMethod(MethodType.GET);/*** 2. 提交录音文件识别结果查询请求* 以轮询的方式进行识别结果的查询,直到服务端返回的状态描述为“SUCCESS”或错误描述,则结束轮询。*/String result = null;while (true) {try {CommonResponse getResponse = client.getCommonResponse(getRequest);System.err.println("识别查询结果:" + getResponse.getData());if (getResponse.getHttpStatus() != 200) {break;}JSONObject rootObj = JSONObject.parseObject(getResponse.getData());String statusText = rootObj.getString(KEY_STATUS_TEXT);if (STATUS_RUNNING.equals(statusText) || STATUS_QUEUEING.equals(statusText)) {// 继续轮询,注意设置轮询时间间隔。Thread.sleep(10000);}else {// 状态信息为成功,返回识别结果;状态信息为异常,返回空。if (STATUS_SUCCESS.equals(statusText)) {result = rootObj.getString(KEY_RESULT);// 状态信息为成功,但没有识别结果,则可能是由于文件里全是静音、噪音等导致识别为空。if(result == null) {result = "";}}break;}} catch (Exception e) {e.printStackTrace();}}return result;}public static void main(String args[]) throws Exception {//写出文本路径文件String path = "C:\\Users\\Administrator\\Desktop\\" +System.currentTimeMillis()+".txt";//txt数据List<String> list = new ArrayList<>();final String accessKeyId = "你的_accessKeyId";final String accessKeySecret = "你的_accessKeySecret";//创建识别项目就有final String appKey = "你的_appKey";//oss存储音频文件地址String fileLink = "http://aabbcc/voice_word.mp3";FileTransJavaDemo demo = new FileTransJavaDemo(accessKeyId, accessKeySecret);// 第一步:提交录音文件识别请求,获取任务ID用于后续的识别结果轮询。String taskId = demo.submitFileTransRequest(appKey, fileLink);System.out.println("taskId_"+taskId);if (taskId != null) {System.out.println("录音文件识别请求成功,task_id: " + taskId);}else {System.out.println("录音文件识别请求失败!");return;}// 第二步:根据任务ID轮询识别结果。String result = demo.getFileTransResult(taskId);if (result != null) {System.out.println("录音文件识别结果查询成功:" + result);JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(result);JSONArray jsonArray = (JSONArray)jsonObject.get("Sentences");
// StringBuffer stringBuffer = new StringBuffer();for (Object strTwo : jsonArray) {cn.hutool.json.JSONObject text = JSONUtil.parseObj(strTwo);String word = text.get("Text").toString();
// stringBuffer.append(word);list.add(word);System.out.println(word);}
// list.add(stringBuffer.toString());//写出.txt文件FileUtil.writeLines(list, new File(path), "utf-8");System.out.println("文件voiceToWord_写出成功!");}else {System.out.println("录音文件识别结果查询失败!");}}
}