Java案例如何实现语音识别?

wen python案例 1

本文目录导读:

Java案例如何实现语音识别?

  1. 使用云端语音识别API(推荐)
  2. 使用WebSocket实时语音识别(流式识别)
  3. 使用本地离线引擎(无需网络)
  4. 完整案例:文件转文字(百度云)
  5. 方案对比与选择建议

使用云端语音识别API(推荐)

这是最成熟、准确率最高的方式,常见服务商有:

1 百度语音识别(国内常用)

<!-- Maven依赖 -->
<dependency>
    <groupId>com.baidu.aip</groupId>
    <artifactId>aip-java-sdk</artifactId>
    <version>4.16.20</version>
</dependency>
import com.baidu.aip.speech.AipSpeech;
import org.json.JSONObject;
public class BaiduSpeechRecognition {
    // 设置APPID/AK/SK
    public static final String APP_ID = "你的AppId";
    public static final String API_KEY = "你的API Key";
    public static final String SECRET_KEY = "你的Secret Key";
    public static void main(String[] args) {
        // 初始化客户端
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 识别音频文件(支持pcm/wav/amr)
        JSONObject res = client.asr("test.pcm", "pcm", 16000, null);
        System.out.println(res.toString(2));
        // 提取识别结果
        String result = res.getJSONArray("result").getString(0);
        System.out.println("识别结果: " + result);
    }
}

2 腾讯云语音识别

<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.1064</version>
</dependency>
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.*;
public class TencentASR {
    public static void main(String[] args) {
        try {
            // 实例化认证对象
            Credential cred = new Credential("SecretId", "SecretKey");
            HttpProfile httpProfile = new HttpProfile();
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            AsrClient client = new AsrClient(cred, "ap-guangzhou", clientProfile);
            // 请求对象
            CreateRecTaskRequest req = new CreateRecTaskRequest();
            req.setEngineModelType("16k_zh");
            req.setChannelNum(1);
            req.setResTextFormat(0);
            req.setSourceType(0); // 0: 语音URL, 1: 本地文件
            // 设置音频数据(Base64编码)
            req.setData("音频的Base64编码");
            CreateRecTaskResponse resp = client.CreateRecTask(req);
            System.out.println(CreateRecTaskResponse.toJsonString(resp));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3 阿里云语音识别

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-nls20160907</artifactId>
    <version>2.0.2</version>
</dependency>

使用WebSocket实时语音识别(流式识别)

适合需要实时反馈的应用场景(如语音助手、实时转写):

// 以百度实时语音识别为例
import com.baidu.aip.speech.AipSpeech;
import com.baidu.speech.restapi.common.DemoException;
import com.baidu.speech.restapi.stream.*;
public class RealTimeASR {
    public static void main(String[] args) throws Exception {
        // 1. 获取token
        AuthService auth = new AuthService();
        String token = auth.getToken("API_KEY", "SECRET_KEY");
        // 2. 初始化WebSocket客户端
        AsrClient client = new AsrClient(token);
        client.setFormat("pcm");
        client.setRate(16000);
        // 3. 设置回调
        client.setAsrListener(new AsrListener() {
            @Override
            public void onResult(String result) {
                System.out.println("实时识别结果: " + result);
            }
        });
        // 4. 开始识别(从麦克风或音频流获取数据)
        client.start();
        // 模拟发送音频数据
        while (hasAudioData()) {
            byte[] data = readAudioChunk();
            client.send(data);
        }
        // 5. 结束识别
        client.stop();
    }
}

使用本地离线引擎(无需网络)

1 Vosk(推荐,支持多种语言)

<dependency>
    <groupId>com.alphacephei</groupId>
    <artifactId>vosk</artifactId>
    <version>0.3.45</version>
</dependency>
import org.vosk.*;
import org.vosk.LibVosk;
import javax.sound.sampled.*;
public class VoskLocalASR {
    public static void main(String[] args) throws Exception {
        // 设置模型路径(需提前下载模型)
        LibVosk.setLogLevel(0);
        Model model = new Model("model/vosk-model-small-cn-0.22");
        Recognizer recognizer = new Recognizer(model, 16000);
        // 从麦克风获取音频
        AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();
        byte[] buffer = new byte[4096];
        while (true) {
            int bytesRead = line.read(buffer, 0, buffer.length);
            if (recognizer.acceptWaveForm(buffer, bytesRead)) {
                String result = recognizer.getResult();
                System.out.println("识别结果: " + result);
            }
        }
    }
}

2 CMU Sphinx(开源但准确率较低)

<dependency>
    <groupId>edu.cmu.sphinx</groupId>
    <artifactId>sphinx4-core</artifactId>
    <version>5prealpha-SNAPSHOT</version>
</dependency>

完整案例:文件转文字(百度云)

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.SpeechRecognitionResponse;
import org.json.JSONObject;
public class FileToText {
    // 从环境变量读取凭证(推荐)
    private static final String APP_ID = System.getenv("BAIDU_APP_ID");
    private static final String API_KEY = System.getenv("BAIDU_API_KEY");
    private static final String SECRET_KEY = System.getenv("BAIDU_SECRET_KEY");
    public static void main(String[] args) {
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 识别本地文件
        JSONObject result = client.asr("audio/test.wav", "wav", 16000, null);
        if (result.getInt("err_no") == 0) {
            String text = result.getJSONArray("result").getString(0);
            System.out.println("转换文本: " + text);
        } else {
            System.out.println("识别失败: " + result.getString("err_msg"));
        }
    }
}

方案对比与选择建议

方案 准确率 延迟 网络需求 成本 适用场景
百度/阿里云 高(95%+) 200-500ms 需要 按量付费 通用应用
Vosk 中(85%) 实时 不需要 免费 离线场景
CMU Sphinx 低(70%) 实时 不需要 免费 教学实验
WebSocket流式 低延迟 需要 较高 实时对话

推荐路线

  • 生产环境:优先选择百度/腾讯/阿里云
  • 离线/嵌入式:Vosk + 中文模型
  • 实时对话:WebSocket流式识别

需注意:使用云服务前需要先注册账号、获取API密钥,并确保音频格式(采样率、编码)符合服务要求。

抱歉,评论功能暂时关闭!