Advertisement
miklis

music secrets2

Jun 21st, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. import math, wave, array
  2. duration = 3 # seconds
  3. freq = 440 # of cycles per second (Hz) (frequency of the sine waves)
  4. volume = 1. # percent
  5. data = [] # signed short integer (-32768 to 32767) data
  6. sampleRate = 44100 # of samples per second (standard)
  7. numChan = 1 # of channels (1: mono, 2: stereo)
  8. dataSize = 2 # 2 bytes because of using signed short integers => bit depth = 16
  9. numSamplesPerCyc = int(sampleRate / freq)
  10. numSamples = sampleRate * duration
  11.  
  12. def num_to_wav(numbers):
  13. def SPLIT(x): return (x%256, (x/256)+256*(x<0))
  14. #return ''.join(map(lambda t: chr(t), reduce(lambda x,y: x+y, map(lambda x: SPLIT(x), numbers)))) - INEFFICIENT WAY
  15. return array.array('h', numbers).tostring()
  16. def wav_to_num(stream):
  17. def JOIN(x): return x[0]+256*((x[1]-128)+128*(2*(x[1]<128)-1))
  18. temp=map(lambda x: ord(x), stream)
  19. return map(lambda x: JOIN(x), zip(temp[::2],temp[1::2]))
  20. def write_wav(stream, path):
  21. #takes a stream of symbols and records a wav
  22. f = wave.open(path, 'w')
  23. f.setparams((numChan, dataSize, sampleRate, numSamples, "NONE", "Uncompressed"))
  24. f.writeframes(stream)
  25. f.close()
  26. def read_wav(path):
  27. #takes a wav and return a stream
  28. f = wave.open(path, 'r')
  29. result=f.readframes(-1)
  30. f.close()
  31. return result
  32.  
  33. def add_lists(lists):
  34. '''adding multiple lists like vectors'''
  35. if len(set([len(lists[i]) for i in range(len(lists))]))<>1: raise ValueError('length is not synchronised')
  36. else: return [sum([x[i] for x in lists]) for i in range(len(lists[0]))]
  37.  
  38.  
  39. def ADSR_env(x):
  40. if x<0.2: return 5*x
  41. if x<1: return 1-0.75*(x-0.2)
  42. if x<2: return 0.4
  43. return max(0, 0.4-0.4*(x-2.0))
  44. def instrument(weigths, k=440, sampleRate=44100.):
  45. s=sum(weigths)
  46. weigths=[n/s for n in weigths]
  47. lists=[]
  48. for j in range(len(weigths)):
  49. division=[]
  50. for i in range(numSamples):
  51. argument=float(i)/sampleRate
  52. x=weigths[j] * math.sin(math.pi * 2 * argument * ((j+1)*k))
  53. component=int(-32767 * x * ADSR_env(argument))
  54. division.append(component)
  55. lists.append(division)
  56. return add_lists(lists)
  57.  
  58. #I'm adding 3 different waves of 440Hz, 660Hz and 220Hz.
  59. for n in instrument([5.,4.,3.]): data.append(n)
  60. write_wav(num_to_wav(data),'trial4.wav')
  61. from time import*
  62. t=time()
  63. a=wav_to_num(read_wav('trial4.wav'))
  64. print time()-t
  65. print data==a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement