1.申请科大语音转写APPID
2.maven pom.xml引入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>com.iflytek</groupId>
<artifactId>Msc</artifactId>
<version>1.0.1</version>
</dependency>
3.代码实现
package com.iflytek;
import com.iflytek.cloud.speech.*;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class VoiceTool {
/**
* 音频文件
*/
public static String audioPath = "D:\\***\\16k_10.pcm";///home/asr/my.pcm"; 也可转成wav格式
private StringBuilder sb;
private SpeechRecognizer speechRecognizer;
private Object lock = new Object();
public VoiceTool(String appId){
SpeechUtility.createUtility(SpeechConstant.APPID + "=" + appId);
}
public String RecognizePcmfileByte(MultipartFile audioFile) {
sb = new StringBuilder();
try {
if (speechRecognizer == null) {//参数可以在配置文件设置
speechRecognizer = SpeechRecognizer.createRecognizer();
speechRecognizer.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");
speechRecognizer.setParameter( SpeechConstant.RESULT_TYPE, "plain" );
speechRecognizer.setParameter(SpeechConstant.VAD_BOS,"5000");//前端点超时,
speechRecognizer.setParameter(SpeechConstant.VAD_EOS,"10000");//后端点超时要与运行SDK时配置的一样
}
speechRecognizer.startListening(recListener);
byte[] buffer = audioFile.getBytes();
if (buffer == null || buffer.length == 0) {
speechRecognizer.cancel();
} else {
int lenRead = buffer.length;
speechRecognizer.writeAudio( buffer, 0, lenRead );
speechRecognizer.stopListening();
synchronized (lock) {
lock.wait();//主线程等待
}
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private RecognizerListener recListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
}
@Override
public void onEndOfSpeech() {
}
/**
* 获取听写结果
*/
@Override
public void onResult(RecognizerResult results, boolean islast) {
//用json解析器解析为json格式
String text = results.getResultString();
sb.append(text);
//log.info("解析结果:"+curRet.toString());
if( islast ) {
synchronized (lock) {
lock.notify();//子线程唤醒
}
}
}
@Override
public void onVolumeChanged(int volume) {
}
@Override
public void onError(SpeechError error) {
}
@Override
public void onEvent(int eventType, int arg1, int agr2, String msg) {
}
};
public static void main(String args[]) throws IOException {
VoiceTool iatTool = new VoiceTool("你的APPID");
File file = new File(audioPath);
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
String result = iatTool.RecognizePcmfileByte(multipartFile);
System.out.println(result);
}
}