Skip to content

Instantly share code, notes, and snippets.

@brdrcol
Created December 4, 2016 20:34
Show Gist options
  • Save brdrcol/acdcaefd78bb8893107e55eeb60aaef3 to your computer and use it in GitHub Desktop.
Save brdrcol/acdcaefd78bb8893107e55eeb60aaef3 to your computer and use it in GitHub Desktop.
Play sinusoids with pygame/numpy
import pygame
import numpy as np
from pprint import pprint
import time
import math
notes = {
'g3':196.00,
'gs3':207.65,
'a3':220.00,
'as3':233.08,
'b3':246.94,
'c4': 261.63,
'cs4': 277.18,
'd4': 293.66,
'ds4': 311.13,
'e4': 329.63,
'f4': 349.23,
'fs4': 369.99,
'g4': 392.00,
'gs4': 415.30,
'a4': 440.00,
'as4': 466.16,
'b4': 493.88,
'c5': 523.25,
'cs5': 554.37,
'd5': 587.33,
'ds5': 622.25,
'e5': 659.25,
'f5': 698.46,
'fs5': 739.99,
'g5': 783.99,
'gs5': 830.61,
'a5': 880.00,
'as5': 932.33,
'b5': 987.77,
'c6': 1046.50
}
def getSound(freq=261.63):
length = np.int(np.ceil(48000/freq))
samples = np.zeros(length, dtype=np.int16)
for i in range(0,length):
samples[i] = np.uint16((32768/4)*np.sin(i*2*np.pi*(freq/48000)))
sound = pygame.mixer.Sound(samples)
return sound
pygame.mixer.init(48000, 16, 1, 1024)
sounds = {}
for k, v in notes.items():
sounds[k] = getSound(freq=v)
print("Starting")
series = ['c4', 'e4', 'g5', 'b5', 'g4', 'b4', 'd5', 'f4', 'as4', 'd4', 'f5', 'a3', 'c4', '', '', '', '']
j = 0
duration = 0.5
for i,s in enumerate(series):
if not s == '':
print("Starting " + str(i))
sounds[s].play(loops=-1)
if i > 2:
print("Stopping " + str(j))
sounds[series[j]].stop()
j += 1
time.sleep(duration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment