Skip to content

Instantly share code, notes, and snippets.

@pathunstrom
Created November 30, 2017 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pathunstrom/48343b44663930876cbcd8730ca5fff0 to your computer and use it in GitHub Desktop.
Save pathunstrom/48343b44663930876cbcd8730ca5fff0 to your computer and use it in GitHub Desktop.
Pygame Sounds manually building buffers.
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