Google Speech API returns NULL

徘徊边缘 提交于 2019-12-13 06:48:48

问题


Trying to develop a speech to text application using Google's API with below code

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();
  }

  }
}

however after running the class (which sends .flac file to Google api) am getting as "{"result":[]}" Instead of the utterances of the audio file converted to text, what could be the cases Google returns the result as "{"result":[]}"?


回答1:


Ran into the same issue my self. I found that is was the format of the flac file. It needs to be 16-bit PCM and mono otherwise you get the null result back. I use http://www.audacityteam.org/ to check/convert my files.



来源:https://stackoverflow.com/questions/35331295/google-speech-api-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!