-
-
Save rowntreerob/f5e089d6a17644a93de6 to your computer and use it in GitHub Desktop.
Android Post to google speech-api v2 using httpsurlconnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void onPostButton(View view) { | |
final AtomicInteger inctr = new AtomicInteger(flacfilelist.size()); | |
Log.d(TAG, "starting loop atomctr " +flacfilelist.size()); | |
myspeech.reset(); | |
Handler messageHandler; | |
String speechUrl = ParseApplication.getInstance().SPEECH_FILE_FLAC; | |
// apicnt=0; // these should be threadsafe | |
// apiresp=0; | |
//call to postParse() should wait for a signal from the handler of the last one. | |
for(String apifil : flacfilelist){ | |
byte[] data2 = mapFileIn(apifil); | |
//These will have to be sent to the storage in serialized form | |
// filter for what=99 so u can increment serialized speech requests saying DONE-SPEECH | |
messageHandler = new Handler() { | |
public void handleMessage(Message msg) { | |
super.handleMessage(msg); | |
String mmsg = (String)msg.obj; | |
if(mmsg.equalsIgnoreCase("error"))mmsg = ""; | |
myspeech.setSpeech(msg.what,mmsg); | |
Log.d(TAG, "onPostHandle " +msg.what +" "+mmsg); | |
if(msg.what == 0){ | |
ParseApplication.getInstance().SPEECH_DONE = true; | |
if(ParseApplication.AUDIO_DONE && | |
ParseApplication.PIC_DONE && | |
!ParseApplication.VIDEO_REQUESTED){ | |
postHerokuVideo(); | |
}else if(ParseApplication.SPEECH_DONE && | |
ParseApplication.AUDIO_DONE && | |
ParseApplication.PIC_DONE && | |
ParseApplication.VIDEO_DONE){ | |
postParseFinl(); | |
} | |
}; | |
// apiresp++; | |
// if (apiresp > 0 && apiresp == apicnt){} u are DONESPEECH | |
} | |
}; | |
//can not be on MAIN thrd | |
this.openHttpsPostConnection( speechUrl, messageHandler, data2, inctr); | |
// Log.d(TAG, "INLOOPR " +apicnt); | |
// apicnt++; | |
//belo not rite spot to ++ should be on stream finish write the request | |
// inctr.incrementAndGet(); | |
} //end for LOOP | |
Toast.makeText(Speech_API_Activity.this, "Conversion requests sent " + flacfilelist.size(), | |
Toast.LENGTH_SHORT).show(); | |
for(int z=0;z<flacfilelist.size();z++){flacfilelist.remove(z);} | |
} | |
private byte[] mapFileIn(String infile){ | |
FileInputStream fis = null; | |
try { | |
fis = new FileInputStream(new File(getFilesDir(),infile)); | |
FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory | |
int sz = (int)fc.size(); | |
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); | |
byte[] data2 = new byte[bb.remaining()]; | |
Log.d("ParseStarter", "mapfil "+ sz + " " +bb.remaining()); | |
bb.get(data2); | |
fis.close(); | |
return data2; | |
} catch (FileNotFoundException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public void openHttpsPostConnection(String urlStr, Handler mhandler, byte[] data, AtomicInteger cntr) { | |
final Handler mymsgH2 = mhandler; | |
final String murl = urlStr; | |
final byte[] mdata = data; | |
final AtomicInteger mcount = cntr; | |
new Thread () { | |
public void run() { | |
String line; | |
HttpsURLConnection httpConn = null; | |
InputStream in = null; | |
ByteBuffer buff; | |
buff = ByteBuffer.wrap(mdata); | |
byte[] destdata = new byte[2048]; | |
int resCode = -1; | |
OutputStream out = null; | |
// int http_status; | |
try { | |
URL url = new URL(murl); | |
URLConnection urlConn = url.openConnection(); | |
if (!(urlConn instanceof HttpsURLConnection)) { | |
throw new IOException ("URL is not an Https URL"); | |
} | |
httpConn = (HttpsURLConnection)urlConn; | |
httpConn.setAllowUserInteraction(false); | |
httpConn.setInstanceFollowRedirects(true); | |
httpConn.setRequestMethod("POST"); | |
httpConn.setDoOutput(true); | |
httpConn.setChunkedStreamingMode(0); //TransferType: chunked | |
httpConn.setRequestProperty("Content-Type", "audio/x-flac; rate=16000"); | |
// httpConn.setRequestProperty("Content-Type", "audio/amr; rate=8000"); | |
// httpConn.connect(); | |
// this opens a connection, then sends POST & headers. | |
out = httpConn.getOutputStream(); | |
Log.d(TAG, "HTTPimpl " +out.getClass().getName()); | |
//beyond 15 sec duration just simply writing the file | |
// does not seem to work. So buffer it and delay to simulate | |
// bufferd microphone delivering stream of speech | |
// re: net.http.ChunkedOutputStream.java | |
while(buff.remaining() >= destdata.length){ | |
buff.get(destdata); | |
out.write(destdata); | |
// Thread.sleep(60); //30K per second on FLAC 22050 | |
//check response? | |
}; | |
byte[] lastr = new byte[buff.remaining()]; | |
buff.get(lastr, 0, lastr.length); | |
out.write(lastr); | |
// out.write(FINAL_CHUNK); //no idea why this be reqd but , it works with longer recordings | |
// out.flush(); | |
out.close(); | |
//if GT file being sent to google then serialize them | |
Log.d(TAG, "IO fin on data write to POST speech"); | |
resCode = httpConn.getResponseCode(); | |
Log.d(TAG, "speech-api resp " +resCode); | |
BufferedReader is = | |
new BufferedReader(new InputStreamReader(httpConn.getInputStream())); | |
// Pattern pattern = Pattern.compile("result.*alternative.*transcript"); | |
// Matcher matcher = pattern.matcher(""); | |
//bug random responses just getting closed prior to the full read | |
while ((line = is.readLine( )) != null) { | |
Log.d(TAG, "Speech chnl io " +line); | |
// if (matcher.find( )) { | |
if(line.length()>19 && resCode > 100 && resCode < HttpURLConnection.HTTP_UNAUTHORIZED){ | |
Message msg = Message.obtain(); | |
msg.what=mcount.decrementAndGet(); //flac file serializer | |
Log.d(TAG, "httpresp write msgloop " +msg.what); | |
msg.obj=line; // string obj. 4 JSON parser | |
mymsgH2.sendMessage(msg); | |
} | |
} | |
if(resCode >= HttpURLConnection.HTTP_UNAUTHORIZED){ | |
Message msg = Message.obtain(); | |
msg.what=mcount.decrementAndGet(); //flac file serializer | |
msg.obj="error"; // string obj. 4 JSON parser | |
mymsgH2.sendMessage(msg); | |
} | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
finally {httpConn.disconnect();} | |
} | |
}.start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
would not work using apache http 4.3 ( bad JSON response from google IMO )
had to use HttpsURLConnection instead.