snd2array.py 757 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Python tool to convert a sound to C array.
  2. #
  3. # Pass sound file name to this sctipt as a parameter. The file must be in raw
  4. # mono 8kHz 8bit PCM format.
  5. #
  6. # by drummyfish
  7. # released under CC0 1.0.
  8. import sys
  9. even = True
  10. val = 0
  11. result = ""
  12. first = True
  13. count = 0
  14. with open(sys.argv[1], "rb") as f:
  15. while True:
  16. byte = f.read(1)
  17. if byte == b"":
  18. break
  19. byte = ord(byte)
  20. quantized = byte / 16
  21. if even:
  22. val = quantized << 4
  23. else:
  24. val = val | quantized
  25. count += 1
  26. if first:
  27. first = False
  28. else:
  29. result += ","
  30. if count % 20 == 0:
  31. result += "\n"
  32. result += str(val)
  33. even = not even
  34. print("uint8_t sound[" + str(count) + "] = {\n" + result + "\n}")