I'm studying a simple application "speech to text" via Google Speech API v2. I have made a Java project and downloaded a flac file (good-morning-google.flac
) to test it.
When I send the flac file to the google server, I get the following error:
java.io.IOException: Error writing to server Finished at sun.net.www.protocol.http.HttpURLConnection.writeRequests(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.writeRequests(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at java.net.HttpURLConnection.getResponseMessage(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseMessage(Unknown Source) at speech.JavaSoundRecorder.main(JavaSoundRecorder.java:140)
I think that the problem is in the definition of the url, but I'm not sure. Could anybody help me to resolve it?
This is my code to connect to google server:
String urlString = "https://www.google.com/speech-api/v2/recognize?output=json&lang=en-US&" + key;
try {
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuilder stringBuilder;
connection.setDefaultUseCaches(true);
connection.setConnectTimeout(20000);
connection.setReadTimeout(60000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac;rate=44100");
/*Write the audio on bufferI/O*/
File file = new File("C:/Travail/audio/good-morning-google.flac");
byte[] buffer = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(buffer);
fis.close();
OutputStream os = connection.getOutputStream();
os.write(buffer);
os.close();
connection.connect();
System.out.println("connect to google server!");
connection.getResponseMessage();
System.out.println("receive the reponse!");
InputStreamReader inputStreamReader = new InputStreamReader(
connection.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
stringBuilder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
System.out.println(stringBuilder);
// JSONObject jsonResponse = new JSONObject(stringBuilder.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}