从语音识别意图中记录/保存音频

Sli*_*lim 24 android speech-recognition speech-to-text

在提出这个问题之前,我检查了所有与此问题相关的stackoverflow其他线程没有任何成功,所以请不要回答其他线程的链接,:)

我想保存/记录谷歌识别服务用于语音操作的音频(使用RecognizerIntent或SpeechRecognizer).

我经历了很多想法:

  1. 来自RecognitionListener的onBufferReceived:我知道,这不起作用,只是测试它看看会发生什么,而onBufferReceived永远不会被调用(使用JB 4.3在galaxy nexus上测试)
  2. 使用媒体录像机:不工作.它突破了语音识别.麦克风只允许一个操作
  3. 试图找到识别服务在执行语音之前保存临时音频文件到文本api复制它的地方,但没有成功

我几乎绝望,但我只是注意到Google Keep应用程序正在做我需要做的事情!我使用logcat稍微调试了keep应用程序,app也调用了"RecognizerIntent.ACTION_RECOGNIZE_SPEECH"(就像我们开发人员一样)来触发语音到文本.但是,如何继续保存音频?它可以成为隐藏的api吗?是谷歌"作弊":)?

谢谢您的帮助

最好的祝福

Ift*_*tah 20

@ Kaarel的答案几乎完成 - 结果音频进入intent.getData()并可以使用ContentResolver

不幸的是,返回的AMR文件质量很低 - 我无法找到获得高质量录制的方法.我试过的除"audio/AMR"以外的任何值都返回null intent.getData().

如果您找到了获得高质量录音的方法 - 请评论或添加答案!

public void startSpeechRecognition() {
   // Fire an intent to start the speech recognition activity.
   Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
   // secret parameters that when added provide audio url in the result
   intent.putExtra("android.speech.extra.GET_AUDIO_FORMAT", "audio/AMR");
   intent.putExtra("android.speech.extra.GET_AUDIO", true);

   startActivityForResult(intent, "<some code you choose>");
}

// handle result of speech recognition
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // the resulting text is in the getExtras:
    Bundle bundle = data.getExtras();
    ArrayList<String> matches = bundle.getStringArrayList(RecognizerIntent.EXTRA_RESULTS)
    // the recording url is in getData:
    Uri audioUri = data.getData();
    ContentResolver contentResolver = getContentResolver();
    InputStream filestream = contentResolver.openInputStream(audioUri);
    // TODO: read audio file from inputstream
}
Run Code Online (Sandbox Code Playgroud)

  • 进一步的翻译是: InputStream filestream = contentResolver.openInputStream(audioUri); byte[] 缓冲区 = 新字节 [filestream.available()]; 文件流。读取(缓冲区);OutputStream outStream = new FileOutputStream(audiofile); outStream.write(缓冲区);请确保您将在此处将文件描述符\命名为 audiofile (3认同)
  • 这可能是一个很长的拍摄但是..,我得到了这个工作。然而,它打开了一个对话,我通过实现 RecognitionListener 绕过了它,但是 public void onResults(Bundle results) 因为我覆盖不包含 Intent 并且我找不到任何方法来获得 Intent 所以我可以不检索 URI。 (2认同)
  • @Haider Saleem 我使用 RecognizerIntent 来识别用户的语音,至少我可以通过 MediaPlayer 重播他/她的语音。 (2认同)

Kaa*_*rel 9

上次我查看时,Google Keep会设置这些额外内容:

  • android.speech.extra.GET_AUDIO_FORMAT:audio/AMR
  • android.speech.extra.GET_AUDIO:是的

这些未记录为Android文档的一部分,因此它们不构成Android API.此外,Google Keep不会依赖识别器意图来考虑这些额外内容.如果这些额外内容被Google推广和记录,那肯定会很好.

要了解Google Keep在调用时设置的附加内容,请RecognizerIntent实施响应RecognizerIntent并打印出所有附加内容的应用.您也可以安装Kõnele(http://kaljurand.github.io/K6nele/),这是一个实现RecognizerIntent.当Kõnele由Google Keep发布时,请长按扳手形设置图标.这显示了有关呼叫者的一些技术细节,还包括传入的附加内容.

@Iftah的答案解释了Google Keep如何将音频录音返回给来电者RecognizerIntent.

  • @Slim @Kaarel结果是`intent.getData()`不在`getExtras()`中.结果是您需要使用`ContentResolver`打开的内容URL (2认同)