make-barker-audios.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/python3
  2. """
  3. This script creates useful barker code files
  4. """
  5. import subprocess
  6. import argparse
  7. from logging import basicConfig
  8. from barker import BARKERS
  9. def get_parser():
  10. p = argparse.ArgumentParser()
  11. p.add_argument("fname")
  12. p.add_argument(
  13. "--barker-sequence-length", type=int, default=5, choices=BARKERS.keys()
  14. )
  15. p.add_argument(
  16. "--barker-freq-1", default=1000, type=int, help='Known as "+1" in barker code'
  17. )
  18. p.add_argument(
  19. "--barker-freq-2", default=500, type=int, help='Known as "-1" in barker code'
  20. )
  21. p.add_argument("--duration", default=100, type=int)
  22. p.add_argument(
  23. "--log-level",
  24. default="WARNING",
  25. choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
  26. )
  27. return p
  28. def compress(seq):
  29. """
  30. Make repetition more explicit
  31. >>> compress([1,1,10,100,100,100])
  32. [[2, 1], [1, 10], [3, 100]]
  33. """
  34. if not seq:
  35. return []
  36. out = [[1, seq[0]]]
  37. for elem in seq[1:]:
  38. if elem == out[-1][1]:
  39. out[-1][0] += 1
  40. else:
  41. out.append([1, elem])
  42. return out
  43. def main():
  44. args = get_parser().parse_args()
  45. basicConfig(level=args.log_level)
  46. barker_sequence = BARKERS[args.barker_sequence_length]
  47. barker_seq_duration = compress(barker_sequence)
  48. synth = []
  49. symbol_map = {1: str(args.barker_freq_1), -1: str(args.barker_freq_2)}
  50. for howmany, symbol in barker_seq_duration:
  51. freq = symbol_map[symbol]
  52. part = ["synth", "%.2f" % (howmany * args.duration / 1000.0), "sin", freq, ":"]
  53. synth.extend(part)
  54. synth.pop() # remove trailing colon
  55. cmd = ["sox", "-n", args.fname] + synth
  56. subprocess.check_call(cmd)
  57. if __name__ == "__main__":
  58. main()