Skip to content

Instantly share code, notes, and snippets.

@non

non/migraine.py Secret

Last active Mar 9, 2021
Embed
What would you like to do?
import sys
width = 1 # 1-byte, 8 bits
rate = 8000 # 8 kHz
try:
assert len(sys.argv[1:]) == 2
loc = sys.argv[1]
if sys.argv[2].endswith('ms'):
nsamples = int(sys.argv[2][:-2]) * (rate / 1000)
elif sys.argv[2].endswith('s'):
nsamples = int(sys.argv[2][:-1]) * rate
elif sys.argv[2].endswith('m'):
nsamples = int(sys.argv[2][:-1]) * (rate * 60)
else:
nsamples = int(sys.argv[2])
except:
print('')
print('usage: %s PATH TIME' % sys.argv[0])
print(' PATH: a file path or - for direct playback')
print(' TIME: a duration in seconds (4s), milliseconds (4000ms), or samples (32000)')
print('example: %s - 61s # plays 61 seconds of noise' % sys.argv[0])
print('')
sys.exit(1)
def u8(n): return n % 256
def mix(n1, n2): return (n1 >> 1) + (n2 >> 1)
def tempo(n): return n * 8192
def song1(t): return t * ((t>>13|t>>7) & 63 & t>>5)
def song2(t): return t * ((t>>12|t>>5) & 127 & t>>7)
def song3(t): return t * u8(u8(t>>8)+u8(t>>9)) * 100
def gen(t):
tt = t % tempo(60)
n1, n2, n3 = song1(t), song2(t), song3(t)
if tt < tempo(8): return n1
if tt < tempo(24): return mix(n1, n2)
if tt < tempo(40): return n2
if tt < tempo(52): return mix(n2, n3)
return n3
frames = bytearray()
def run(t0, count):
for t in range(t0, t0 + count):
frames.append(u8(gen(t)))
def save(path, count):
import wave
w = wave.open(path, 'wb')
w.setnchannels(1) # mono
w.setsampwidth(width)
w.setframerate(rate)
run(0, count)
w.writeframes(frames)
w.close()
print('wrote %r' % path)
def play(count):
import pyaudio
p = pyaudio.PyAudio()
fmt = p.get_format_from_width(width)
stream = p.open(format=fmt, channels=1, rate=rate, output=True)
for t in range(0, count, 1024):
run(t, 1024)
stream.write(bytes(frames))
frames.clear()
stream.stop_stream()
stream.close()
p.terminate()
if loc == "-":
play(nsamples)
else:
save(loc, nsamples)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment