item_audio.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // Copyright 2017 Eric Zhou. 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. package base64Captcha
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "fmt"
  10. "io"
  11. "math/rand"
  12. )
  13. //ItemAudio captcha-audio-engine return type.
  14. type ItemAudio struct {
  15. answer string
  16. body *bytes.Buffer
  17. digitSounds [][]byte
  18. //rng siprng
  19. }
  20. // newAudio returns a new audio captcha with the given digits, where each digit
  21. // must be in range 0-9. Digits are pronounced in the given language. If there
  22. // are no sounds for the given language, English is used.
  23. // Possible values for lang are "en", "ja", "ru", "zh".
  24. func newAudio(id string, digits []byte, lang string) *ItemAudio {
  25. a := new(ItemAudio)
  26. if sounds, ok := digitSounds[lang]; ok {
  27. a.digitSounds = sounds
  28. } else {
  29. a.digitSounds = digitSounds["en"]
  30. }
  31. numsnd := make([][]byte, len(digits))
  32. for i, n := range digits {
  33. snd := a.randomizedDigitSound(n)
  34. setSoundLevel(snd, 1.5)
  35. numsnd[i] = snd
  36. }
  37. // Random intervals between digits (including beginning).
  38. intervals := make([]int, len(digits)+1)
  39. intdur := 0
  40. for i := range intervals {
  41. dur := randIntRange(sampleRate, sampleRate*2) // 1 to 2 seconds
  42. intdur += dur
  43. intervals[i] = dur
  44. }
  45. // Generate background sound.
  46. bg := a.makeBackgroundSound(a.longestDigitSndLen()*len(digits) + intdur)
  47. // Create buffer and write audio to it.
  48. sil := makeSilence(sampleRate / 5)
  49. bufcap := 3*len(beepSound) + 2*len(sil) + len(bg) + len(endingBeepSound)
  50. a.body = bytes.NewBuffer(make([]byte, 0, bufcap))
  51. // Write prelude, three beeps.
  52. a.body.Write(beepSound)
  53. a.body.Write(sil)
  54. a.body.Write(beepSound)
  55. a.body.Write(sil)
  56. a.body.Write(beepSound)
  57. // Write digits.
  58. pos := intervals[0]
  59. for i, v := range numsnd {
  60. mixSound(bg[pos:], v)
  61. pos += len(v) + intervals[i+1]
  62. }
  63. a.body.Write(bg)
  64. // Write ending (one beep).
  65. a.body.Write(endingBeepSound)
  66. return a
  67. }
  68. // encodedLen returns the length of WAV-encoded audio captcha.
  69. func (a *ItemAudio) encodedLen() int {
  70. return len(waveHeader) + 4 + a.body.Len()
  71. }
  72. func (a *ItemAudio) makeBackgroundSound(length int) []byte {
  73. b := a.makeWhiteNoise(length, 4)
  74. for i := 0; i < length/(sampleRate/10); i++ {
  75. snd := reversedSound(a.digitSounds[rand.Intn(10)])
  76. //snd = changeSpeed(snd, a.rng.Float(0.8, 1.2))
  77. place := rand.Intn(len(b) - len(snd))
  78. setSoundLevel(snd, randFloat64Range(0.04, 0.08))
  79. mixSound(b[place:], snd)
  80. }
  81. return b
  82. }
  83. func (a *ItemAudio) randomizedDigitSound(n byte) []byte {
  84. s := a.randomSpeed(a.digitSounds[n])
  85. setSoundLevel(s, randFloat64Range(0.85, 1.2))
  86. return s
  87. }
  88. func (a *ItemAudio) longestDigitSndLen() int {
  89. n := 0
  90. for _, v := range a.digitSounds {
  91. if n < len(v) {
  92. n = len(v)
  93. }
  94. }
  95. return n
  96. }
  97. func (a *ItemAudio) randomSpeed(b []byte) []byte {
  98. pitch := randFloat64Range(0.95, 1.1)
  99. return changeSpeed(b, pitch)
  100. }
  101. func (a *ItemAudio) makeWhiteNoise(length int, level uint8) []byte {
  102. noise := randBytes(length)
  103. adj := 128 - level/2
  104. for i, v := range noise {
  105. v %= level
  106. v += adj
  107. noise[i] = v
  108. }
  109. return noise
  110. }
  111. // WriteTo writes captcha audio in WAVE format into the given io.Writer, and
  112. // returns the number of bytes written and an error if any.
  113. func (a *ItemAudio) WriteTo(w io.Writer) (n int64, err error) {
  114. // Calculate padded length of PCM chunk data.
  115. bodyLen := uint32(a.body.Len())
  116. paddedBodyLen := bodyLen
  117. if bodyLen%2 != 0 {
  118. paddedBodyLen++
  119. }
  120. totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen
  121. // Header.
  122. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size
  123. copy(header, waveHeader)
  124. // Put the length of whole RIFF chunk.
  125. binary.LittleEndian.PutUint32(header[4:], totalLen)
  126. // Put the length of WAVE chunk.
  127. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen)
  128. // Write header.
  129. nn, err := w.Write(header)
  130. n = int64(nn)
  131. if err != nil {
  132. return
  133. }
  134. // Write data.
  135. n, err = a.body.WriteTo(w)
  136. n += int64(nn)
  137. if err != nil {
  138. return
  139. }
  140. // Pad byte if chunk length is odd.
  141. // (As header has even length, we can check if n is odd, not chunk).
  142. if bodyLen != paddedBodyLen {
  143. w.Write([]byte{0})
  144. n++
  145. }
  146. return
  147. }
  148. // EncodeB64string encodes a sound to base64 string
  149. func (a *ItemAudio) EncodeB64string() string {
  150. var buf bytes.Buffer
  151. if _, err := a.WriteTo(&buf); err != nil {
  152. panic(err)
  153. }
  154. return fmt.Sprintf("data:%s;base64,%s", MimeTypeAudio, base64.StdEncoding.EncodeToString(buf.Bytes()))
  155. }