Created
October 28, 2016 12:46
-
-
Save piotrrojek/8bf5820d6bb00edf05bd6296e3bd6372 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package main | |
import ( | |
"bytes" | |
"encoding/base64" | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
) | |
func main() { | |
f, err := os.Open("./sample.wav") | |
if err != nil { | |
log.Fatal(err) | |
} | |
b, err := ioutil.ReadAll(f) | |
if err != nil { | |
log.Fatal(err) | |
} | |
text, err := fetchTranscription(b) | |
if err != nil { | |
log.Fatal("couldn't transcribe:", err) | |
} | |
fmt.Println(text) | |
} | |
type speechReq struct { | |
Config struct { | |
Encoding string `json:"encoding"` | |
SampleRate int `json:"sampleRate"` | |
} `json:"config"` | |
Audio struct { | |
Content string `json:"content"` | |
} `json:"audio"` | |
} | |
func fetchTranscription(b []byte) (string, error) { | |
var req speechReq | |
req.Config.Encoding = "LINEAR16" | |
req.Config.SampleRate = 16000 | |
req.Audio.Content = base64.StdEncoding.EncodeToString(b) | |
j, err := json.Marshal(req) | |
if err != nil { | |
return "", fmt.Errorf("could not encode request: %v", err) | |
} | |
client := &http.Client{} | |
request, err := http.NewRequest("POST", "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key="+os.Getenv("GOOGLE_SPEECH_API"), bytes.NewReader(j)) | |
if err != nil { | |
return "", fmt.Errorf("couldn't not transcribe: %v", err) | |
} | |
res, err := client.Do(request) | |
if err != nil { | |
return "", err | |
} | |
var data struct { | |
Error struct { | |
Code int | |
Message string | |
Status string | |
} | |
Results []struct { | |
Alternatives []struct { | |
Transcript string | |
Confidence float64 | |
} | |
} | |
} | |
if err := json.NewDecoder(res.Body).Decode(&data); err != nil { | |
return "", fmt.Errorf("couldn't decode response: %v", err) | |
} | |
if data.Error.Code != 0 { | |
return "", fmt.Errorf("speech API error: %d %s %s", | |
data.Error.Code, data.Error.Status, data.Error.Message) | |
} | |
if len(data.Results) == 0 || len(data.Results[0].Alternatives) == 0 { | |
return "", fmt.Errorf("no transcription found: %+v", data) | |
} | |
return data.Results[0].Alternatives[0].Transcript, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment