|
|
1. 添加依赖项
在 app/build.gradle 文件中添加Google Cloud Speech依赖:
- dependencies {
- implementation 'com.google.cloud:google-cloud-speech:2.5.1'
- }
复制代码
2. 设置认证
Google Speech-to-Text需要服务账户认证:
·创建Google Cloud项目并启用Speech-to-Text API
·下载服务账户密钥文件(JSON格式)
·将密钥文件放在 app/src/main/res/raw/ 目录下
3. 修改发送音频数据的方法
替换当前的 sendWavFile 方法,使用Google API:
- private void sendToGoogleSpeechAPI(byte[] audioData) {
- new Thread(() -> {
- try {
- // 初始化Google Speech客户端
- SpeechSettings speechSettings = SpeechSettings.newBuilder()
- .setCredentialsProvider(FixedCredentialsProvider.create(
- ServiceAccountCredentials.fromStream(
- context.getResources().openRawResource(R.raw.your_service_key)
- )
- ))
- .build();
-
- SpeechClient speechClient = SpeechClient.create(speechSettings);
-
- // 配置识别参数
- RecognitionConfig config = RecognitionConfig.newBuilder()
- .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
- .setSampleRateHertz(8000)
- .setLanguageCode("en-US")
- .build();
-
- // 构建请求
- RecognitionAudio audio = RecognitionAudio.newBuilder()
- .setContent(ByteString.copyFrom(audioData))
- .build();
-
- RecognizeRequest request = RecognizeRequest.newBuilder()
- .setConfig(config)
- .setAudio(audio)
- .build();
-
- // 发送请求并获取结果
- RecognizeResponse response = speechClient.recognize(request);
- List<SpeechRecognitionResult> results = response.getResultsList();
-
- // 处理识别结果
- if (!results.isEmpty()) {
- String transcript = results.get(0).getAlternativesList().get(0).getTranscript();
- Log.d("MyAudioRecord", "识别结果: " + transcript);
- }
-
- speechClient.close();
- } catch (Exception e) {
- Log.e("MyAudioRecord", "Google Speech API错误: " + e.getMessage());
- }
- }).start();
- }
复制代码
4. 调用修改
在 stopRecord 方法中调用新的API方法:
- // 替换原来的 sendWavFile() 调用
- sendToGoogleSpeechAPI(completeAudioData);
复制代码
这样就可以将当前项目中的音频数据发送到Google Speech-to-Text API进行识别了。
|
|