一、为何选择百度语音识别API?
百度语音识别API作为国内领先的语音技术解决方案,具备高精度、低延迟、多语言支持等核心优势。其支持实时语音转文字、长语音识别、中英文混合识别等场景,且提供灵活的调用方式(RESTful API或SDK集成),尤其适合需要快速实现语音交互功能的Android应用开发者。相较于其他方案,百度API的文档完善、社区活跃度高,且提供免费试用额度,极大降低了开发门槛。
二、开发环境准备
1. 注册百度智能云账号
访问百度智能云官网,完成实名认证后创建“语音识别”应用,获取API Key和Secret Key。这两个密钥是后续鉴权的核心凭证,需妥善保管。
2. 配置Android Studio项目
- 新建项目:选择“Empty Activity”模板,确保最低SDK版本≥Android 5.0(API 21)。
- 添加网络权限:在
AndroidManifest.xml中声明:<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.RECORD_AUDIO" />
- 依赖库引入:在
app/build.gradle中添加网络请求库(如OkHttp)和JSON解析库(如Gson):dependencies {implementation 'com.squareup.okhttp3
4.9.0'implementation 'com.google.code.gson
2.8.6'}
三、核心实现步骤
1. 获取Access Token
百度API采用OAuth2.0鉴权机制,需通过API Key和Secret Key动态获取Token:
public String getAccessToken(String apiKey, String secretKey) throws IOException {OkHttpClient client = new OkHttpClient();String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials" +"&client_id=" + apiKey + "&client_secret=" + secretKey;Request request = new Request.Builder().url(url).build();try (Response response = client.newCall(request).execute()) {String responseBody = response.body().string();JSONObject jsonObject = new JSONObject(responseBody);return jsonObject.getString("access_token");}}
关键点:Token有效期为30天,建议缓存并定期刷新。
2. 录制音频并发送请求
使用MediaRecorder录制PCM格式音频(采样率16000Hz,单声道,16位):
private void startRecording() {String filePath = getExternalFilesDir(null) + "/audio.pcm";MediaRecorder recorder = new MediaRecorder();recorder.setAudioSource(MediaRecorder.AudioSource.MIC);recorder.setOutputFormat(MediaRecorder.OutputFormat.PCM_16BIT);recorder.setAudioEncoder(MediaRecorder.AudioEncoder.PCM_16BIT);recorder.setOutputFile(filePath);recorder.prepare();recorder.start();// 录制10秒后停止new Handler().postDelayed(() -> {recorder.stop();recorder.release();recognizeSpeech(filePath);}, 10000);}
3. 调用语音识别API
将音频文件转换为Base64编码后发送POST请求:
private void recognizeSpeech(String filePath) throws IOException {String accessToken = getAccessToken("your_api_key", "your_secret_key");String url = "https://vop.baidu.com/server_api?cuid=your_device_id&token=" + accessToken;// 读取音频文件并Base64编码byte[] audioData = Files.readAllBytes(Paths.get(filePath));String audioBase64 = Base64.encodeToString(audioData, Base64.DEFAULT);// 构建请求体JSONObject jsonParams = new JSONObject();jsonParams.put("format", "pcm");jsonParams.put("rate", 16000);jsonParams.put("channel", 1);jsonParams.put("cuid", "your_device_id");jsonParams.put("token", accessToken);jsonParams.put("speech", audioBase64);jsonParams.put("len", audioData.length);// 发送请求OkHttpClient client = new OkHttpClient();RequestBody body = RequestBody.create(audioBase64,MediaType.parse("application/json"));Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {String responseBody = response.body().string();JSONObject result = new JSONObject(responseBody);String text = result.getJSONArray("result").getString(0);Log.d("SpeechRecognition", "识别结果: " + text);}}
四、进阶优化与错误处理
1. 实时语音识别
通过WebSocket实现流式识别,需修改请求头并分块发送音频数据:
// 使用OkHttp的WebSocketOkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url("wss://vop.baidu.com/websocket_api?token=" + accessToken).build();WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {@Overridepublic void onMessage(WebSocket webSocket, String text) {// 处理实时识别结果}});// 分块发送音频数据...
2. 常见错误处理
| 错误码 | 原因 | 解决方案 |
|---|---|---|
| 100 | 无效Token | 检查API Key/Secret Key是否正确 |
| 110 | Token过期 | 重新获取Token |
| 111 | 音频格式错误 | 确认采样率、编码格式 |
| 112 | 音频过长 | 分段发送或降低采样率 |
五、性能优化建议
- 网络优化:使用HTTP/2或WebSocket减少延迟。
- 音频预处理:在客户端进行降噪(如使用WebRTC的NS模块)。
- 离线识别:结合百度离线识别SDK降低流量消耗。
- 多线程处理:将音频录制、网络请求放在独立线程避免UI卡顿。
六、总结与展望
通过本文的步骤,开发者可在4小时内完成从环境搭建到功能实现的完整流程。百度语音识别API的灵活性和高精度使其成为Android语音交互的首选方案。未来,随着端侧AI的发展,可进一步探索模型轻量化部署,实现完全离线的语音识别功能。
扩展资源:
- 百度语音识别官方文档
- Android音频处理开源库:AndroidAudioRecorder
- 性能测试工具:Android Profiler