drums.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import pyaudio
  2. import socket
  3. import optparse
  4. import tarfile
  5. import wave
  6. import cStringIO as StringIO
  7. import array
  8. import time
  9. from packet import Packet, CMD, stoi, OBLIGATE_POLYPHONE
  10. parser = optparse.OptionParser()
  11. parser.add_option('-t', '--test', dest='test', action='store_true', help='As a test, play all samples then exit')
  12. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose')
  13. parser.add_option('-V', '--volume', dest='volume', type='float', default=1.0, help='Set the volume factor (nominally [0.0, 1.0], but >1.0 can be used to amplify with possible distortion)')
  14. parser.add_option('-r', '--rate', dest='rate', type='int', default=44100, help='Audio sample rate for output and of input files')
  15. parser.add_option('-u', '--uid', dest='uid', default='', help='User identifier of this client')
  16. parser.add_option('-p', '--port', dest='port', default=13676, type='int', help='UDP port to listen on')
  17. parser.add_option('--repeat', dest='repeat', action='store_true', help='If a note plays longer than a sample length, keep playing the sample')
  18. parser.add_option('--cut', dest='cut', action='store_true', help='If a note ends within a sample, stop playing that sample immediately')
  19. parser.add_option('-n', '--max-voices', dest='max_voices', default=-1, type='int', help='Only support this many notes playing simultaneously (earlier ones get dropped)')
  20. options, args = parser.parse_args()
  21. MAX = 0x7fffffff
  22. MIN = -0x80000000
  23. IDENT = 'DRUM'
  24. if not args:
  25. print 'Need at least one drumpack (.tar.bz2) as an argument!'
  26. parser.print_usage()
  27. exit(1)
  28. DRUMS = {}
  29. for fname in args:
  30. print 'Reading', fname, '...'
  31. tf = tarfile.open(fname, 'r')
  32. names = tf.getnames()
  33. for nm in names:
  34. if not (nm.endswith('.wav') or nm.endswith('.raw')) or len(nm) < 5:
  35. continue
  36. frq = int(nm[:-4])
  37. if options.verbose:
  38. print '\tLoading frq', frq, '...'
  39. fo = tf.extractfile(nm)
  40. if nm.endswith('.wav'):
  41. wf = wave.open(fo)
  42. if wf.getnchannels() != 1:
  43. print '\t\tWARNING: Channel count wrong: got', wf.getnchannels(), 'expecting 1'
  44. if wf.getsampwidth() != 4:
  45. print '\t\tWARNING: Sample width wrong: got', wf.getsampwidth(), 'expecting 4'
  46. if wf.getframerate() != options.rate:
  47. print '\t\tWARNING: Rate wrong: got', wf.getframerate(), 'expecting', options.rate, '(maybe try setting -r?)'
  48. frames = wf.getnframes()
  49. data = ''
  50. while len(data) < wf.getsampwidth() * frames:
  51. data += wf.readframes(frames - len(data) / wf.getsampwidth())
  52. elif nm.endswith('.raw'):
  53. data = fo.read()
  54. frames = len(data) / 4
  55. if options.verbose:
  56. print '\t\tData:', frames, 'samples,', len(data), 'bytes'
  57. if frq in DRUMS:
  58. print '\t\tWARNING: frequency', frq, 'already in map, overwriting...'
  59. DRUMS[frq] = data
  60. if options.verbose:
  61. print len(DRUMS), 'sounds loaded'
  62. PLAYING = []
  63. class SampleReader(object):
  64. def __init__(self, buf, total, amp):
  65. self.buf = buf
  66. self.total = total
  67. self.cur = 0
  68. self.amp = amp
  69. def read(self, bytes):
  70. if self.cur >= self.total:
  71. return ''
  72. res = ''
  73. while self.cur < self.total and len(res) < bytes:
  74. data = self.buf[self.cur % len(self.buf):self.cur % len(self.buf) + bytes - len(res)]
  75. self.cur += len(data)
  76. res += data
  77. arr = array.array('i')
  78. arr.fromstring(res)
  79. for i in range(len(arr)):
  80. arr[i] = int(arr[i] * self.amp)
  81. return arr.tostring()
  82. def __repr__(self):
  83. return '<SR (%d) @%d / %d A:%f>'%(len(self.buf), self.cur, self.total, self.amp)
  84. def gen_data(data, frames, tm, status):
  85. fdata = array.array('l', [0] * frames)
  86. torem = set()
  87. for src in set(PLAYING):
  88. buf = src.read(frames * 4)
  89. if not buf:
  90. torem.add(src)
  91. continue
  92. samps = array.array('i')
  93. samps.fromstring(buf)
  94. if len(samps) < frames:
  95. samps.extend([0] * (frames - len(samps)))
  96. for i in range(frames):
  97. fdata[i] += samps[i]
  98. for src in torem:
  99. PLAYING.remove(src)
  100. for i in range(frames):
  101. fdata[i] = max(MIN, min(MAX, fdata[i]))
  102. fdata = array.array('i', fdata)
  103. return (fdata.tostring(), pyaudio.paContinue)
  104. pa = pyaudio.PyAudio()
  105. stream = pa.open(rate=options.rate, channels=1, format=pyaudio.paInt32, output=True, frames_per_buffer=64, stream_callback=gen_data)
  106. if options.test:
  107. for frq in sorted(DRUMS.keys()):
  108. print 'Current playing:', PLAYING
  109. print 'Playing:', frq
  110. data = DRUMS[frq]
  111. PLAYING.add(SampleReader(data, len(data), 1.0))
  112. time.sleep(len(data) / (4.0 * options.rate))
  113. print 'Done'
  114. exit()
  115. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  116. sock.bind(('', options.port))
  117. #signal.signal(signal.SIGALRM, sigalrm)
  118. while True:
  119. data = ''
  120. while not data:
  121. try:
  122. data, cli = sock.recvfrom(4096)
  123. except socket.error:
  124. pass
  125. pkt = Packet.FromStr(data)
  126. print 'From', cli, 'command', pkt.cmd
  127. if pkt.cmd == CMD.KA:
  128. pass
  129. elif pkt.cmd == CMD.PING:
  130. sock.sendto(data, cli)
  131. elif pkt.cmd == CMD.QUIT:
  132. break
  133. elif pkt.cmd == CMD.PLAY:
  134. frq = pkt.data[2]
  135. if frq not in DRUMS:
  136. print 'WARNING: No such instrument', frq, ', ignoring...'
  137. continue
  138. rdata = DRUMS[frq]
  139. rframes = len(rdata) / 4
  140. dur = pkt.data[0]+pkt.data[1]/1000000.0
  141. dframes = int(dur * options.rate)
  142. if not options.repeat:
  143. dframes = max(dframes, rframes)
  144. if not options.cut:
  145. dframes = rframes * ((dframes + rframes - 1) / rframes)
  146. amp = max(min(options.volume * pkt.as_float(3), 1.0), 0.0)
  147. PLAYING.append(SampleReader(rdata, dframes * 4, amp))
  148. if options.max_voices >= 0:
  149. while len(PLAYING) > options.max_voices:
  150. PLAYING.pop(0)
  151. #signal.setitimer(signal.ITIMER_REAL, dur)
  152. elif pkt.cmd == CMD.CAPS:
  153. data = [0] * 8
  154. data[0] = OBLIGATE_POLYPHONE
  155. data[1] = stoi(IDENT)
  156. for i in xrange(len(options.uid)/4 + 1):
  157. data[i+2] = stoi(options.uid[4*i:4*(i+1)])
  158. sock.sendto(str(Packet(CMD.CAPS, *data)), cli)
  159. # elif pkt.cmd == CMD.PCM:
  160. # fdata = data[4:]
  161. # fdata = struct.pack('16i', *[i<<16 for i in struct.unpack('16h', fdata)])
  162. # QUEUED_PCM += fdata
  163. # print 'Now', len(QUEUED_PCM) / 4.0, 'frames queued'
  164. else:
  165. print 'Unknown cmd', pkt.cmd