Facebook
From Ample Dolphin, 5 Years ago, written in Python.
Embed
Download Paste or View Raw
Hits: 224
  1. import pyaudio
  2. import numpy as np
  3.  
  4. p = pyaudio.PyAudio()
  5.  
  6. volume = 1.0     # range [0.0, 1.0]
  7. fs = 44100       # sampling rate, Hz, must be integer
  8. duration = 0.6  # in seconds, may be float
  9. f = 440.0        # sine frequency, Hz, may be float
  10.  
  11.  
  12. #this goes from A2 5 octaves up in A major
  13. key = np.arange(25,74)
  14. major = np.array([0,2,4,5,7,9,11])
  15. new = major + 11
  16. while major[-1]<=74:
  17.     major = np.concatenate((major,new))
  18.     new = new + 12
  19.  
  20. values = []
  21.  
  22. for i in key:
  23.     j = np.abs(int((3*i)/np.cos(i)+1))
  24.     while j>=len(major):
  25.         j=j-len(major)
  26.     values.append(j)
  27.  
  28.  
  29. # for paFloat32 sample values must be in range [-1.0, 1.0]
  30. stream = p.open(format=pyaudio.paFloat32,
  31.                 channels=1,
  32.                 rate=fs,
  33.                 output=True)
  34.  
  35. # play. May repeat with different volume values (if done interactively)
  36. while True:
  37.     for elem in values:
  38.         # generate samples, note conversion to float32 array
  39.         samples = (np.sin(2 * np.pi * np.arange(fs * duration) * (2**((major[elem]-49)/12)*440.0) / fs)).astype(np.float32)
  40.         stream.write(volume*samples)
  41.         print(key[elem])
  42.  
  43. stream.stop_stream()
  44. stream.close()
  45.  
  46. p.terminate()
  47.  
  48.