Last active
December 22, 2016 17:55
-
-
Save nomelif/f0b8aeb106df3aec15bdd3b75bbe8c14 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
import pygame | |
import numpy as np | |
def eventGenerator(eventcode, bufferSize): # Event loop; wait while PyGame is OK, yield to the signal generator when pygame asks for signal | |
# Buffer | |
for chunk in range(bufferSize): | |
yield | |
while True: | |
evt = pygame.event.wait() | |
if evt.type == eventcode: | |
yield | |
def soundGenerator(): # This just generates a signal (sine wave here) | |
t = 0 | |
for event in eventGenerator(57, 4): # Event code, buffer size | |
yield np.sin(np.arange(1024)*(2*np.pi*400/41000)+t) # Yield the data; wait until it is awoken by the eventGenerator | |
t = t + 2*np.pi*440*1024/41000 | |
def outputLoop(inputStream): # This basically works with PyGame's sound system | |
# Initialisation | |
SRATE=41000 # sample rate in Hz | |
pygame.display.init() | |
pygame.mixer.pre_init(SRATE, -16, 1, 1024) | |
pygame.init() | |
channel=pygame.mixer.Channel(1) | |
channel.set_endevent(57) | |
# Main loop | |
for chunk in inputStream: # Runs every time the eventGenerator asks for it to | |
snd=pygame.sndarray.make_sound(np.int16(np.clip(chunk*(2**15), -2**15, 2**15-1))) # Pull a sound from the soundGenerator and transform it into the right range | |
channel.queue(snd) # Queue the sound up | |
outputLoop(soundGenerator()) # Setup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment