all repos — captcha @ 2ef763a3c268ec446cc50418f06780537db3db18

Go package captcha implements generation and verification of image and audio CAPTCHAs.

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