-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (68 loc) · 2.09 KB
/
main.go
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
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"github.com/hegedustibor/htgo-tts"
"github.com/kennygrant/sanitize"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
const audioFolder = "audio"
const defaultPort = 1337
const volume = 2
func main() {
http.HandleFunc("/", serveSpeech)
port := defaultPort
if os.Getenv("TTSAAS_PORT") != "" {
var err error
port, err = strconv.Atoi(os.Getenv("TTSAAS_PORT"))
if err != nil {
log.Fatalf("Port environment variable set, but could not convert it to int %s\n", err)
}
}
log.Printf("Starting text to speech as a service on port %d\n", port)
if err := http.ListenAndServe(":"+strconv.Itoa(port), nil); err != nil {
panic(err)
}
}
func serveSpeech(w http.ResponseWriter, r *http.Request) {
addCORSHeader(w)
urlParts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
if len(urlParts) < 1 {
http.Error(w, "bad request", http.StatusBadRequest)
log.Println("Bad request")
return
}
sentence := sanitize.BaseName(urlParts[0])
// Save audio file to audio folder
speech := htgotts.Speech{Folder: audioFolder, Language: "no"}
err := speech.Speak(sentence)
if err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
log.Printf("Error converting text to speech: %s\n", err)
return
}
fileURI := audioFolder + "/" + sentence + ".mp3"
loudFileURI := audioFolder + "/" + sentence + "LOUD" + ".mp3"
cmdString := fmt.Sprintf("ffmpeg -y -i %s -filter:a \"volume=%d\" %s", fileURI, volume, loudFileURI)
cmd := exec.Command("bash", "-c", cmdString)
buf, err := cmd.Output()
if err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
log.Printf("Error increasing audio volume: %s: %s\n", err, string(buf))
log.Printf(cmdString)
return
}
time.Sleep(500 * time.Millisecond)
http.ServeFile(w, r, loudFileURI)
}
func addCORSHeader(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}