main.go 2.1 KB

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