generate/main.go (view raw)
1// generate is a tool to generate sounds.go from WAVE files.
2//
3// It creates (or rewrites) sounds.go in the parent directory.
4package main
5
6import (
7 "fmt"
8 "os"
9 "io"
10 "io/ioutil"
11 "log"
12 "path"
13)
14
15const headerLen = 44
16
17var langs = []string{"en", "ru"}
18
19func writeVar(w io.Writer, b []byte, prefix string) {
20 i := 0
21 for j, v := range b {
22 fmt.Fprintf(w, "0x%02x,", v)
23 i++
24 if i == 11 {
25 fmt.Fprintf(w, "\n")
26 if j != len(b)-1 {
27 fmt.Fprintf(w, prefix)
28 }
29 i = 0
30 } else {
31 if j != len(b)-1 {
32 fmt.Fprintf(w, " ")
33 }
34 }
35 }
36 if i > 0 {
37 fmt.Fprintf(w, "\n")
38 }
39}
40
41func writeFileRep(pcm io.Writer, name, prefix string) {
42 b, err := ioutil.ReadFile(name)
43 if err != nil {
44 log.Fatalf("%s", err)
45 }
46 writeVar(pcm, b[headerLen:], prefix)
47}
48
49func writeSingle(pcm io.Writer, name string) {
50 fmt.Fprintf(pcm, "\nvar %sSound = []byte{\n\t", name)
51 writeFileRep(pcm, name+".wav", "\t")
52 fmt.Fprintf(pcm, "}\n")
53}
54
55func writeDigitSounds(pcm io.Writer, lang string) {
56 fmt.Fprintf(pcm, "\t\"%s\" : [][]byte{\n", lang)
57 for i := 0; i <= 9; i++ {
58 fmt.Fprintf(pcm, "\t\t{ // %d\n\t\t\t", i)
59 writeFileRep(pcm, path.Join(lang, fmt.Sprintf("%d.wav", i)), "\t\t\t")
60 fmt.Fprintf(pcm, "\t\t},\n")
61 }
62 fmt.Fprintf(pcm, "\t},\n")
63}
64
65func main() {
66 pcm, err := os.Create(path.Join("..", "sounds.go"))
67 if err != nil {
68 log.Fatalf("%s", err)
69 }
70 defer pcm.Close()
71 fmt.Fprintf(pcm, `package captcha
72
73// This file has been generated from .wav files using generate.go.
74
75var waveHeader = []byte{
76 0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45,
77 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
78 0x40, 0x1f, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00,
79 0x64, 0x61, 0x74, 0x61,
80}
81
82// Byte slices contain raw 8 kHz unsigned 8-bit PCM data (without wav header).
83
84`)
85 fmt.Fprintf(pcm, "var digitSounds = map[string][][]byte{\n")
86 for _, lang := range langs {
87 writeDigitSounds(pcm, lang)
88 }
89 fmt.Fprintf(pcm, "}\n")
90 writeSingle(pcm, "beep")
91}