Android Studio集成百度语音识别API:从入门到实战指南

一、为何选择百度语音识别API?

百度语音识别API作为国内领先的语音技术解决方案,具备高精度、低延迟、多语言支持等核心优势。其支持实时语音转文字、长语音识别、中英文混合识别等场景,且提供灵活的调用方式(RESTful API或SDK集成),尤其适合需要快速实现语音交互功能的Android应用开发者。相较于其他方案,百度API的文档完善、社区活跃度高,且提供免费试用额度,极大降低了开发门槛。

二、开发环境准备

1. 注册百度智能云账号

访问百度智能云官网,完成实名认证后创建“语音识别”应用,获取API KeySecret Key。这两个密钥是后续鉴权的核心凭证,需妥善保管。

2. 配置Android Studio项目

  • 新建项目:选择“Empty Activity”模板,确保最低SDK版本≥Android 5.0(API 21)。
  • 添加网络权限:在AndroidManifest.xml中声明:
    1. <uses-permission android:name="android.permission.INTERNET" />
    2. <uses-permission android:name="android.permission.RECORD_AUDIO" />
  • 依赖库引入:在app/build.gradle中添加网络请求库(如OkHttp)和JSON解析库(如Gson):
    1. dependencies {
    2. implementation 'com.squareup.okhttp3:okhttp:4.9.0'
    3. implementation 'com.google.code.gson:gson:2.8.6'
    4. }

    三、核心实现步骤

    1. 获取Access Token

    百度API采用OAuth2.0鉴权机制,需通过API Key和Secret Key动态获取Token:

    1. public String getAccessToken(String apiKey, String secretKey) throws IOException {
    2. OkHttpClient client = new OkHttpClient();
    3. String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" +
    4. "&client_id=" + apiKey + "&client_secret=" + secretKey;
    5. Request request = new Request.Builder().url(url).build();
    6. try (Response response = client.newCall(request).execute()) {
    7. String responseBody = response.body().string();
    8. JSONObject jsonObject = new JSONObject(responseBody);
    9. return jsonObject.getString("access_token");
    10. }
    11. }

    关键点:Token有效期为30天,建议缓存并定期刷新。

2. 录制音频并发送请求

使用MediaRecorder录制PCM格式音频(采样率16000Hz,单声道,16位):

  1. private void startRecording() {
  2. String filePath = getExternalFilesDir(null) + "/audio.pcm";
  3. MediaRecorder recorder = new MediaRecorder();
  4. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  5. recorder.setOutputFormat(MediaRecorder.OutputFormat.PCM_16BIT);
  6. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.PCM_16BIT);
  7. recorder.setOutputFile(filePath);
  8. recorder.prepare();
  9. recorder.start();
  10. // 录制10秒后停止
  11. new Handler().postDelayed(() -> {
  12. recorder.stop();
  13. recorder.release();
  14. recognizeSpeech(filePath);
  15. }, 10000);
  16. }

3. 调用语音识别API

将音频文件转换为Base64编码后发送POST请求:

  1. private void recognizeSpeech(String filePath) throws IOException {
  2. String accessToken = getAccessToken("your_api_key", "your_secret_key");
  3. String url = "https://vop.baidu.com/server_api?cuid=your_device_id&token=" + accessToken;
  4. // 读取音频文件并Base64编码
  5. byte[] audioData = Files.readAllBytes(Paths.get(filePath));
  6. String audioBase64 = Base64.encodeToString(audioData, Base64.DEFAULT);
  7. // 构建请求体
  8. JSONObject jsonParams = new JSONObject();
  9. jsonParams.put("format", "pcm");
  10. jsonParams.put("rate", 16000);
  11. jsonParams.put("channel", 1);
  12. jsonParams.put("cuid", "your_device_id");
  13. jsonParams.put("token", accessToken);
  14. jsonParams.put("speech", audioBase64);
  15. jsonParams.put("len", audioData.length);
  16. // 发送请求
  17. OkHttpClient client = new OkHttpClient();
  18. RequestBody body = RequestBody.create(
  19. audioBase64,
  20. MediaType.parse("application/json")
  21. );
  22. Request request = new Request.Builder()
  23. .url(url)
  24. .post(body)
  25. .build();
  26. try (Response response = client.newCall(request).execute()) {
  27. String responseBody = response.body().string();
  28. JSONObject result = new JSONObject(responseBody);
  29. String text = result.getJSONArray("result").getString(0);
  30. Log.d("SpeechRecognition", "识别结果: " + text);
  31. }
  32. }

四、进阶优化与错误处理

1. 实时语音识别

通过WebSocket实现流式识别,需修改请求头并分块发送音频数据:

  1. // 使用OkHttp的WebSocket
  2. OkHttpClient client = new OkHttpClient();
  3. Request request = new Request.Builder()
  4. .url("wss://vop.baidu.com/websocket_api?token=" + accessToken)
  5. .build();
  6. WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
  7. @Override
  8. public void onMessage(WebSocket webSocket, String text) {
  9. // 处理实时识别结果
  10. }
  11. });
  12. // 分块发送音频数据...

2. 常见错误处理

错误码 原因 解决方案
100 无效Token 检查API Key/Secret Key是否正确
110 Token过期 重新获取Token
111 音频格式错误 确认采样率、编码格式
112 音频过长 分段发送或降低采样率

五、性能优化建议

  1. 网络优化:使用HTTP/2或WebSocket减少延迟。
  2. 音频预处理:在客户端进行降噪(如使用WebRTC的NS模块)。
  3. 离线识别:结合百度离线识别SDK降低流量消耗。
  4. 多线程处理:将音频录制、网络请求放在独立线程避免UI卡顿。

六、总结与展望

通过本文的步骤,开发者可在4小时内完成从环境搭建到功能实现的完整流程。百度语音识别API的灵活性和高精度使其成为Android语音交互的首选方案。未来,随着端侧AI的发展,可进一步探索模型轻量化部署,实现完全离线的语音识别功能。

扩展资源

  • 百度语音识别官方文档
  • Android音频处理开源库:AndroidAudioRecorder
  • 性能测试工具:Android Profiler