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