generate_audio.py 930 B

1234567891011121314151617181920212223242526272829303132333435
  1. import math #import needed modules
  2. import pyaudio #sudo apt-get install python-pyaudio
  3. PyAudio = pyaudio.PyAudio #initialize pyaudio
  4. #See https://en.wikipedia.org/wiki/Bit_rate#Audio
  5. BITRATE = 16000 #number of frames per second/frameset.
  6. FREQUENCY = 500 #Hz, waves per second, 261.63=C4-note.
  7. LENGTH = 1 #seconds to play sound
  8. if FREQUENCY > BITRATE:
  9. BITRATE = FREQUENCY+100
  10. NUMBEROFFRAMES = int(BITRATE * LENGTH)
  11. RESTFRAMES = NUMBEROFFRAMES % BITRATE
  12. WAVEDATA = ''
  13. #generating wawes
  14. for x in range(NUMBEROFFRAMES):
  15. WAVEDATA = WAVEDATA+chr(int(math.sin(x/((BITRATE/FREQUENCY)/math.pi))*127+128))
  16. for x in range(RESTFRAMES):
  17. WAVEDATA = WAVEDATA+chr(128)
  18. p = PyAudio()
  19. stream = p.open(format = p.get_format_from_width(1),
  20. channels = 1,
  21. rate = BITRATE,
  22. output = True)
  23. stream.write(WAVEDATA)
  24. stream.stop_stream()
  25. stream.close()
  26. p.terminate()