Part 2: How To Use Golang With API.ai Artificial Intelligence Service

Part 2 — In this article, we will try out their /tts service.

In part 1 of this series we explored their /query service. Here, we will explore their/tts service which takes text and returns the generated speech (as an audio WAV file).

I have created a folder “apiai” which will hold the Go source code “apiaifile.go”.

C:\go_projects\go\src\github.com\SatishTalim\apiai

We shall be running our program at the command prompt in the folder “apiai” as follows:

go run apiaifile.go

apiaifile.go

Here’s the complete source code:

package main

import (
        "fmt"
        "io"
        "log"
        "net/http"
        "os"
)

func main() {
        url := fmt.Sprintf("https://api.api.ai/v1/tts?v=20150910&text=The+Go+programming+language+rocks!")

        // Create file to store the .wav file
        output, err := os.Create("d.wav")
        if err != nil {
                log.Fatal("Create: ", err)
                return
        }
        defer output.Close()

        // Build the request
        req, err := http.NewRequest("GET", url, nil)
        if err != nil {
                log.Fatal("NewRequest: ", err)
                return
        }        

        // Replace Your_Client_Token with your actual token
        req.Header.Add("Authorization", "Bearer Your_Client_Token")
        req.Header.Add("Accept-language", "en-US" )

        // For control over HTTP client headers,
        // redirect policy, and other settings,
        // create a Client
        // A Client is an HTTP client
        client := &http.Client{}

        // Send the request via a client
        // Do sends an HTTP request and
        // returns an HTTP response
        resp, err := client.Do(req)
        if err != nil {
                log.Fatal("Do: ", err)
                return
        }
        
        // Callers should close resp.Body
        // when done reading from it
        // Defer the closing of the body
        defer resp.Body.Close()       
        
        if _, err := io.Copy(output, resp.Body); err != nil {
                log.Fatal("Copy: ", err)
                return
        }

        fmt.Println("File d.wav downloaded.")
}

https://api.api.ai/v1/tts?v=20150910&text=The+Go+programming+language+rocks!

The above URL processes the phrase “The Go programming language rocks!” and generates an audio file from it.

func Create(name string) (*File, error)

“Create” creates the named file, truncating it if it already exists.

func NewRequest(method, urlStr string, body io.Reader) (*Request, error)

“NewRequest” returns a new “Request” given a method, URL, and an optional body. “NewRequest” returns a “Request” suitable for use with “Client.Do”.

func (h Header) Add(key, value string)

“Add” adds the key, value pair to the header. It appends to any existing values associated with key.

// Replace Your_Client_Token by your actual Client access token 
req.Header.Add(“Authorization”, “Bearer Your_Client_Token”)
req.Header.Add("Accept-language", "en-US" )

A single header “Accept-language” is used to identify TTS language. For each API request, include the above HTTP headers.

client := &http.Client{}

A “Client” is an HTTP client.

resp, err := client.Do(req)

“Do” sends an HTTP request and returns an HTTP response. When “err” is nil, “resp” always contains a non-nil “resp.Body”.

defer resp.Body.Close()

Callers should close “resp.Body” when done reading from it. Use “Defer” for closing the body. “resp.Body” is of type “io.Reader”.

func Copy(dst Writer, src Reader) (written int64, err error)

“Copy” copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.

Here’s the file “d.wav” that got downloaded using our program.

That’s it!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.