Created
July 5, 2017 09:28
-
-
Save notexactlyawe/cd86c087277dd84e2896bbc05dc90468 to your computer and use it in GitHub Desktop.
Whitenoise generating snippet
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 threading | |
import random | |
import Queue | |
import pyaudio | |
import numpy as np | |
SAMPLE_RATE = 44100 | |
DURATION = 0.5 | |
class WhitenoiseSound(threading.Thread): | |
def __init__(self, freq_q, init_freq=10): | |
super(WhitenoiseSound, self).__init__() | |
self.freq = init_freq | |
self.freq_q = freq_q | |
self.stop_request = threading.Event() | |
self.pya = pyaudio.PyAudio() | |
self.stream = self.pya.open(format=pyaudio.paFloat32, | |
channels=1, | |
rate=SAMPLE_RATE, | |
output=True, | |
frames_per_buffer=int(SAMPLE_RATE*DURATION*0.5), | |
stream_callback=self.callback) | |
def run(self): | |
while not self.stop_request.isSet(): | |
try: | |
self.freq = self.freq_q.get(0.1) | |
except Queue.Empty: | |
pass | |
self.stream.stop_stream() | |
self.stream.close() | |
self.pya.terminate() | |
def callback(self, _in_data, frame_count, _time_info, _status): | |
samples = np.zeros(frame_count).astype(np.float32) | |
spacing = (frame_count / self.freq) * 3 | |
last_idx = 0 | |
for idx in range(frame_count): | |
chance = ((idx - last_idx) % spacing) + 0.1 | |
if random.randrange(11) / 10.0 < chance: | |
samples[idx] = random.randrange(11) / 10.0 | |
last_idx = idx | |
return samples, pyaudio.paContinue | |
def join(self, timeout=None): | |
self.stop_request.set() | |
super(WhitenoiseSound, self).join(timeout) | |
if __name__ == "__main__": | |
freq_q = Queue.Queue() | |
gcs = WhitenoiseSound(freq_q) | |
gcs.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment