Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #
  2. # Copyright 2015 Gareth Poole, All Rights Reserved
  3.  
  4. import sys
  5. import math
  6. from array import array
  7.  
  8. sample_rate = 44100
  9.  
  10. def floatToInt(n):
  11. return int(n * 32768)
  12.  
  13. def byteToBits(byte):
  14. bits = []
  15. for i in range(7, -1, -1):
  16. bits += [(byte >> i) & 1]
  17. return bits
  18.  
  19.  
  20. def genSine(freq, length):
  21. samples = []
  22. length_samples = int(length * sample_rate)
  23. period = (1 / freq) * sample_rate
  24. for i in range(0, length_samples):
  25. samples += [floatToInt(math.sin(i * (2 * math.pi) / period))]
  26. return samples
  27.  
  28. def sumSamples(sample_list):
  29. return int(sum(sample_list) / len(sample_list))
  30.  
  31. def sumSignals(signal_list):
  32. return map(sumSamples, zip(*signal_list))
  33.  
  34. def encodeByte(bits, upshift, length):
  35. sines = []
  36. length_samples = int(length * sample_rate)
  37. for i in range(0, 8):
  38. if bits[i]:
  39. sines += [genSine((upshift * 800) + 100 * (i + 1), length)]
  40. else:
  41. sines += [[0] * length_samples]
  42. return sumSignals(sines)
  43.  
  44. def encodeWord(word, length):
  45. byte_signals = [genSine(50, length)] # pilot tone
  46. for i in range(16):
  47. byte_signals += [encodeByte(word[i], i, length)]
  48. return sumSignals(byte_signals)
  49.  
  50. def encodeString(string, length):
  51. words = []
  52. current_word = []
  53. word_position = 0
  54. strlen = len(string)
  55. samples = []
  56.  
  57. for i in range(strlen):
  58. if word_position < 16:
  59. current_word += [byteToBits(string[i])]
  60. word_position += 1
  61. if i == strlen - 1:
  62. words += [current_word] # Otherwise the final word would not get saved
  63. else:
  64. words += [current_word]
  65. current_word = []
  66. word_position = 0
  67.  
  68. for word in words:
  69. lenword = len(word)
  70. if(lenword < 16):
  71. word += [[0,0,0,0,0,0,0,0]] * (16 - lenword)
  72. samples += encodeWord(word, length)
  73.  
  74. return samples
  75.  
  76. infile = open(sys.argv[0], "rb")
  77. outfile = open(sys.argv[1], "wb")
  78. array('h', encodeString(infile.read(), 0.03125)).tofile(outfile)
  79. outfile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement