-
-
Save qaisjp/ced74dfb43f34ae530c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Generate a 440 Hz square waveform in Pygame by building an array of samples and play | |
# it for 5 seconds. Change the hard-coded 440 to another value to generate a different | |
# pitch. | |
# | |
# Run with the following command: | |
# python pygame-play-tone.py | |
from array import array | |
from time import sleep | |
import pygame | |
from pygame.mixer import Sound, get_init, pre_init | |
class Note(Sound): | |
def __init__(self, frequency, volume=.1): | |
self.frequency = frequency | |
Sound.__init__(self, self.build_samples()) | |
self.set_volume(volume) | |
def build_samples(self): | |
period = int(round(get_init()[0] / self.frequency)) | |
samples = array("h", [0] * period) | |
amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 | |
for time in xrange(period): | |
if time < period / 2: | |
samples[time] = amplitude | |
else: | |
samples[time] = -amplitude | |
return samples | |
if __name__ == "__main__": | |
pre_init(44100, -16, 1, 1024) | |
pygame.init() | |
Note(440).play(-1) | |
sleep(5) |
@TrumpetDude That is not a typo. In Python 2 we have both range
and xrange
. The difference is that range
returns an enumeration whereas xrange
returns an iterator.
In Python 3 xrange
was renamed to range
replacing the original range
method.
There are many subtle changes like this between Python 2 and 3 that you might like to be aware of, see the What's New In Python 3.0 article for more examples :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe there is a typo in line 25, saying xrange instead of range. After fixing it, the tone played. How do I send the correction as a pull request/revision?