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