Google语音API返回NULL

时间:2016-02-11 05:16:44

标签: java android speech-to-text google-speech-api

尝试使用带有以下代码的Google API开发语音到文本应用程序

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.testng.annotations.Test;

public class Speech2Text_Test {
@Test
public void f() {

  try{
  Path path = Paths.get("out.flac");
  byte[] data = Files.readAllBytes(path);

  String request = "https://www.google.com/"+
       "speech-api/v2/recognize?"+
       "xjerr=1&client=speech2text&lang=en-US&maxresults=10"+
       "output=json&key=<My Key>";

  URL url = new URL(request);
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();          
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setInstanceFollowRedirects(false);
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
  connection.setRequestProperty("User-Agent", "speech2text");
  connection.setConnectTimeout(60000);
  connection.setUseCaches (false);

  DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
  wr.write(data);
  wr.flush();
  wr.close();
  connection.disconnect();

  System.out.println("Done");

  BufferedReader in = new BufferedReader(
      new InputStreamReader(
      connection.getInputStream()));
       String decodedString;
       while ((decodedString = in.readLine()) != null) {
       System.out.println(decodedString);
       }

  }
  catch(Exception e){
  e.printStackTrace();
  }

  }
}

然而,在运行该类(将.flac文件发送到Google api)后,我得到“{”结果“:[]}”而不是转换为文本的音频文件的话语,Google返回的情况可能是什么结果为“{”result“:[]}”?

enter image description here

1 个答案:

答案 0 :(得分:2)

我自己也遇到了同样的问题。我发现这是flac文件的格式。它需要是16位PCM和单声道,否则你会得到null结果。我使用http://www.audacityteam.org/来检查/转换我的文件。