-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloudSpeechClient.cpp
66 lines (60 loc) · 2.56 KB
/
CloudSpeechClient.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "CloudSpeechClient.h"
#include "network_param.h"
#include <base64.h>
#include <ArduinoJson.h>
CloudSpeechClient::CloudSpeechClient(Authentication authentication)
{
this->authentication = authentication;
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(1000);
client.setCACert(root_ca);
if (!client.connect(server1, 443)) Serial.println("Connection failed!");
}
String ans;
CloudSpeechClient::~CloudSpeechClient() {
client.stop();
WiFi.disconnect();
}
void CloudSpeechClient::PrintHttpBody2(Audio* audio)
{
String enc = base64::encode(audio->paddedHeader, sizeof(audio->paddedHeader));
enc.replace("\n", ""); // delete last "\n"
client.print(enc); // HttpBody2
char** wavData = audio->wavData;
for (int j = 0; j < audio->wavDataSize / audio->dividedWavDataSize; ++j) {
enc = base64::encode((byte*)wavData[j], audio->dividedWavDataSize);
enc.replace("\n", "");// delete last "\n"
client.print(enc); // HttpBody2
}
}
void CloudSpeechClient::Transcribe(Audio* audio) {
String HttpBody1 = "{\"config\":{\"encoding\":\"LINEAR16\",\"sampleRateHertz\":16000,\"languageCode\":\"en-IN\"},\"audio\":{\"content\":\"";
String HttpBody3 = "\"}}\r\n\r\n";
int httpBody2Length = (audio->wavDataSize + sizeof(audio->paddedHeader)) * 4 / 3; // 4/3 is from base64 encoding
String ContentLength = String(HttpBody1.length() + httpBody2Length + HttpBody3.length());
String HttpHeader;
// if (authentication == USE_APIKEY)
HttpHeader = String("POST /v1/speech:recognize?key=") + SpeechApiKey
+ String(" HTTP/1.1\r\nHost: speech.googleapis.com\r\nContent-Type: application/json\r\nContent-Length: ") + ContentLength + String("\r\n\r\n");
// else if (authentication == USE_ACCESSTOKEN)
// HttpHeader = String("POST /v1beta1/speech:syncrecognize HTTP/1.1\r\nHost: speech.googleapis.com\r\nContent-Type: application/json\r\nAuthorization: Bearer ")
// + AccessToken + String("\r\nContent-Length: ") + ContentLength + String("\r\n\r\n");
client.print(HttpHeader);
client.print(HttpBody1);
PrintHttpBody2(audio);
client.print(HttpBody3);
String My_Answer="";
while (!client.available());
while (client.available())
{
char temp = client.read();
My_Answer = My_Answer + temp;
// Serial.write(client.read());
}
Serial.print("My Answer - ");Serial.println(My_Answer);
int postion = My_Answer.indexOf('{');
Serial.println(postion);
ans = My_Answer.substring(postion);
Serial.print("Json daata--");
Serial.print(ans);
}