Last active
September 7, 2017 14:47
-
-
Save jeansch/fc64171d2d728930490f4736fc94bbe4 to your computer and use it in GitHub Desktop.
Play a 440Hz sinus
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
from array import array | |
from time import sleep | |
import math | |
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): | |
tones = [] | |
tones.append(math.sin((1 * time * 2 * math.pi) / period)) | |
samples[time] = int(amplitude * (sum(tones) / len(tones))) | |
return samples | |
if __name__ == "__main__": | |
pre_init(44100, -16, 1, 1024) | |
pygame.init() | |
Note(440).play(-1) | |
sleep(50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment