Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. # Generate a 440 Hz square waveform in Pygame by building an array of samples and play
  2. # it for 5 seconds. Change the hard-coded 440 to another value to generate a different
  3. # pitch.
  4. #
  5. # Run with the following command:
  6. # python pygame-play-tone.py
  7.  
  8. from array import array
  9. from time import sleep
  10.  
  11. import pygame
  12. from pygame.mixer import Sound, get_init, pre_init
  13.  
  14. class Note(Sound):
  15.  
  16. def __init__(self, frequency, volume=.1):
  17. self.frequency = frequency
  18. Sound.__init__(self, self.build_samples())
  19. self.set_volume(volume)
  20.  
  21. def build_samples(self):
  22. period = int(round(get_init()[0] / self.frequency))
  23. samples = array("h", [0] * period)
  24. amplitude = 2 ** (abs(get_init()[1]) - 1) - 1
  25. for time in xrange(period):
  26. if time < period / 2:
  27. samples[time] = amplitude
  28. else:
  29. samples[time] = -amplitude
  30. return samples
  31.  
  32. if __name__ == "__main__":
  33. pre_init(44100, -16, 1, 1024)
  34. pygame.init()
  35. Note(440).play(-1)
  36. sleep(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement