util_audio.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package base64Captcha
  2. import (
  3. "math"
  4. )
  5. const sampleRate = 8000 // Hz
  6. var endingBeepSound []byte
  7. func init() {
  8. endingBeepSound = changeSpeed(beepSound, 1.4)
  9. }
  10. // mixSound mixes src into dst. Dst must have length equal to or greater than
  11. // src length.
  12. func mixSound(dst, src []byte) {
  13. for i, v := range src {
  14. av := int(v)
  15. bv := int(dst[i])
  16. if av < 128 && bv < 128 {
  17. dst[i] = byte(av * bv / 128)
  18. } else {
  19. dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
  20. }
  21. }
  22. }
  23. func setSoundLevel(a []byte, level float64) {
  24. for i, v := range a {
  25. av := float64(v)
  26. switch {
  27. case av > 128:
  28. if av = (av-128)*level + 128; av < 128 {
  29. av = 128
  30. }
  31. case av < 128:
  32. if av = 128 - (128-av)*level; av > 128 {
  33. av = 128
  34. }
  35. default:
  36. continue
  37. }
  38. a[i] = byte(av)
  39. }
  40. }
  41. // changeSpeed returns new PCM bytes from the bytes with the speed and pitch
  42. // changed to the given value that must be in range [0, x].
  43. func changeSpeed(a []byte, speed float64) []byte {
  44. b := make([]byte, int(math.Floor(float64(len(a))*speed)))
  45. var p float64
  46. for _, v := range a {
  47. for i := int(p); i < int(p+speed); i++ {
  48. b[i] = v
  49. }
  50. p += speed
  51. }
  52. return b
  53. }
  54. func makeSilence(length int) []byte {
  55. b := make([]byte, length)
  56. for i := range b {
  57. b[i] = 128
  58. }
  59. return b
  60. }
  61. func reversedSound(a []byte) []byte {
  62. n := len(a)
  63. b := make([]byte, n)
  64. for i, v := range a {
  65. b[n-1-i] = v
  66. }
  67. return b
  68. }