Created
November 30, 2017 06:00
-
-
Save pathunstrom/48343b44663930876cbcd8730ca5fff0 to your computer and use it in GitHub Desktop.
Pygame Sounds manually building buffers.
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
import pygame | |
from itertools import cycle | |
import math | |
RESOLUTION = (800, 800) | |
BITS = 16 | |
MAX_SAMPLE = 2**(BITS - 1) - 1 | |
LEFT_FREQUENCY = 0 | |
RIGHT_FREQUENCY = 450 | |
def left_sample(time): | |
result = int(MAX_SAMPLE * math.sin(2 * math.pi * LEFT_FREQUENCY * time)) | |
print(result) | |
return result | |
def right_sample(time): | |
return int(MAX_SAMPLE * .5 * math.sin(2 * math.pi * RIGHT_FREQUENCY * time)) | |
pygame.mixer.pre_init(44100, -BITS, 2) | |
pygame.init() | |
display = pygame.display.set_mode(RESOLUTION) | |
duration = 1.0 | |
sample_rate = 44100 | |
n_samples = int(duration*sample_rate) | |
buffer = bytes() | |
for s, f in zip(range(n_samples), cycle([left_sample, right_sample])): | |
for b in abs(f(s/sample_rate)).to_bytes(2, byteorder="little"): | |
buffer += b.to_bytes(1, byteorder="little") | |
print(buffer) | |
sound = pygame.mixer.Sound(buffer=buffer) | |
sound.play(loops=-1) | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
pygame.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment