Python synthesizer stuff
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

375 satır
10KB

  1. """
  2. Python audio synthesis framework.
  3. """
  4. from pymod import _ysynth_init, _ysynth_init, _ysynth_set_callback
  5. from math import cos, sin, pi, modf
  6. from itertools import izip
  7. import numpy as np
  8. from scipy.signal import lfilter
  9. __all__ = ['YSynth', 'Sin', 'Cos', 'Saw', 'RevSaw', 'Square', 'Pulse']
  10. class YSynth(object):
  11. """
  12. YSynth synthesis and audio context.
  13. """
  14. def __init__(self, samplerate=44100, channels=2):
  15. """
  16. Setup a simple synthesizer.
  17. samplerate: Samples/second
  18. channels: Number of output channels.
  19. e.g. 1 for mono, 2 for stereo
  20. """
  21. self.context = _ysynth_init(samplerate, channels)
  22. self.samples = 0
  23. self.volume = 0.75
  24. # XXX need to fetch 'acquired' values from ysynth context
  25. self.samplerate = samplerate
  26. self.channels = channels
  27. self.graph = None
  28. self.set_callback(self.default_callback)
  29. def deinit(self):
  30. """
  31. Shutdown synthesizer, afterwards this object becomes useless.
  32. """
  33. if self.context:
  34. _ysynth_shutdown(self.context)
  35. self.context = None
  36. def default_callback(self, channels):
  37. """
  38. Default synthesis callback.
  39. """
  40. # Outputs silence if no graph available
  41. if not self.graph:
  42. return
  43. # Process audio graph
  44. buf_len = channels.shape[0]
  45. self.chunk_size = buf_len
  46. next_chunk = next(self.graph)
  47. # Do we need to mix from mono to stereo?
  48. if len(next_chunk.shape) == 1:
  49. next_chunk = np.dot(np.reshape(next_chunk, (-1, 1)), ((1, 1),))
  50. #print channels.shape, next_chunk.shape
  51. np.round(next_chunk * 32767.5, 0, out=channels)
  52. # Advance sampleclock
  53. self.samples += buf_len
  54. def set_graph(self, graph):
  55. graph.set_synth(self)
  56. self.graph = iter(graph)
  57. def get_graph(self):
  58. return self.graph
  59. def __del__(self):
  60. """
  61. Deinitialise synth before being removed from mem
  62. """
  63. print "Deinitialising"
  64. self.deinit()
  65. def set_callback(self, func):
  66. """
  67. Set audio output function.
  68. Without any callback the synthesizer will simply output silence.
  69. The callback should adhere the following signature:
  70. def callback(channels):
  71. channels shall contain a list of lists and each list
  72. contains a large block of 0.0 floats describing the next set of samples.
  73. Those floats should be set to the chunk of audio.
  74. """
  75. _ysynth_set_callback(self.context, func)
  76. def get_callback(self):
  77. return _ysynth_get_callback(self.context)
  78. class YConstant(object):
  79. """
  80. Unchanging signal output.
  81. """
  82. def __init__(self, const):
  83. self.const = float(const)
  84. def __iter__(self):
  85. return iter(self())
  86. def __call__(self):
  87. while True:
  88. yield self.const
  89. def set_synth(self, synth):
  90. pass
  91. class YAudioGraphNode(object):
  92. """
  93. Base audio graph node
  94. This base class provides YSynth's DSL behaviours such as
  95. adding, substracting and the sample iteration protocol.
  96. """
  97. def __init__(self, *inputs):
  98. self.inputs = []
  99. lens = 0
  100. for stream in inputs:
  101. if not isinstance(stream, YAudioGraphNode):
  102. stream = YConstant(stream)
  103. self.inputs.append(stream)
  104. self.inputs = tuple(self.inputs)
  105. #for stream in inputs:
  106. # if isinstance(stream, YAudioGraphNode):
  107. # pass
  108. # # Make sure all multi-channels share the same size
  109. # if len(stream) != 1:
  110. # if not lens:
  111. # lens = len
  112. # elif lens != len(stream):
  113. # # TODO: Expand error info to contain sizes
  114. # raise ValueError("Cannot combine different sized "
  115. # "multi-channel streams")
  116. #self.channels = lens
  117. def __iter__(self):
  118. """
  119. Initialise graph for synthesis, link to sampleclock.
  120. """
  121. # XXX This function is not graph cycle safe
  122. # FIXME: I need to unpack the channels from the input streams
  123. # multiplex any mono-streams if there are multi-channel streams
  124. # available, and then initialise every set of streams' component
  125. # generator function by calling self with the correct arguments.
  126. # Setup input streams
  127. for stream in self.inputs:
  128. stream.set_synth(self.synth)
  129. # Setup self
  130. # The self.samples variable is used for protecting against
  131. # multiple next() calls, next will only evaluate the next
  132. # set of input samples if the synth's sampleclock has changed
  133. self.samples = self.synth.samples - 1
  134. # XXX self.last_sample is currently not initialised on purpose
  135. # maybe this must be changed at a later time.
  136. # Connect the actual generator components
  137. sample_iter = iter(self(izip(*self.inputs)))
  138. # Build the sample protection function
  139. def sample_func():
  140. """
  141. Make sure multiple next() calls during the same
  142. clock cycle yield the same sample value.
  143. """
  144. while True:
  145. if self.samples != self.synth.samples:
  146. self.last_sample = next(sample_iter)
  147. self.samples = self.synth.samples
  148. yield self.last_sample
  149. return sample_func()
  150. def set_synth(self, synth):
  151. """
  152. Set this component's synthesizer.
  153. This is mainly useful for reading the synth's sampleclock. However every
  154. active component requires a valid synthesizer.
  155. """
  156. self.synth = synth
  157. def get_synth(self, synth):
  158. """
  159. Return this component's synthesizer.
  160. """
  161. return self.synth
  162. def __add__(self, other):
  163. return Adder(self, other)
  164. def __radd__(self, other):
  165. return Adder(other, self)
  166. def __sub__(self, other):
  167. return Subtractor(self, other)
  168. def __rsub__(self, other):
  169. return Subtractor(other, self)
  170. def __mul__(self, other):
  171. return Multiplier(self, other)
  172. def __rmul__(self, other):
  173. return Multiplier(other, self)
  174. def __div__(self, other):
  175. return Divisor(self, other)
  176. def __rdiv__(self, other):
  177. return Divisor(other, self)
  178. def __getitem__(self, delay):
  179. """
  180. Return a delayed version of the output signal.
  181. """
  182. return Delay(self, delay)
  183. def __next__(self):
  184. """
  185. Process next sample.
  186. """
  187. def __call__(self):
  188. raise NotImplementedError("You need to inherit this class")
  189. def process(self, *streams):
  190. raise NotImplementedError("You need to inherit this class")
  191. # Basic signal arithmetic
  192. class Adder(YAudioGraphNode):
  193. def __call__(self, l):
  194. for a, b in l:
  195. yield a + b
  196. class Subtractor(YAudioGraphNode):
  197. def __call__(self, l):
  198. for a, b in l:
  199. yield a - b
  200. class Multiplier(YAudioGraphNode):
  201. def __call__(self, l):
  202. for a, b in l:
  203. yield a * b
  204. class Divisor(YAudioGraphNode):
  205. def __call__(self, l):
  206. for a, b in l:
  207. yield a / b
  208. # Sample delay
  209. class Delay(YAudioGraphNode):
  210. def __call__(self, l):
  211. buf = [0.0] * 4096
  212. samples = 0
  213. for sig, delay in l:
  214. buf[samples] = sig
  215. yield buf[(samples - delay) % 4096]
  216. samples = (samples + 1) % 4096
  217. # Base oscillator class
  218. class YOscillator(YAudioGraphNode):
  219. def __call__(self, l):
  220. def cycle_gen():
  221. """
  222. This function generates the oscillation cycle
  223. upon which all basic decoupled oscillators base their output
  224. signal.
  225. A decoupled oscillator is an oscillator
  226. with its own cycle generator. These oscillators respond well to
  227. incoming frequency changes, but due to the limitations of floating
  228. point are at risk of drifting out of phase, coupled oscillators
  229. are always in phase with each other.
  230. The generated cycle ranges from 0.0 to 1.0 exclusive.
  231. """
  232. last_cycle = [0.0]
  233. for freq, in l:
  234. # The last_cycle will only be a list during the initial
  235. # iteration, perfect for a 'once' statement, we want
  236. # to force the first cycle value to 0.
  237. if isinstance(last_cycle, list):
  238. if isinstance(freq, np.ndarray):
  239. ifreq = freq[0]
  240. else:
  241. ifreq = freq
  242. last_cycle = [-(ifreq / float(self.synth.samplerate))]
  243. # Compute cycle using IIR filter and np.fmod
  244. cycle, last_cycle = lfilter([1], [1, -1], freq /
  245. float(self.synth.samplerate) *
  246. np.ones(self.synth.chunk_size), zi=last_cycle)
  247. yield np.fmod(cycle, 1.0)
  248. last_cycle = np.fmod(last_cycle, 1.0)
  249. return self.oscillate(cycle_gen())
  250. def oscillate(self, l):
  251. raise NotImplementedError("Inherit this class")
  252. # Basic oscillators
  253. class Sin(YOscillator):
  254. """
  255. Sine wave oscillator
  256. """
  257. def oscillate(self, l):
  258. for pos in l:
  259. yield np.sin(2 * pi * pos)
  260. class Cos(YOscillator):
  261. """
  262. Cosine wave oscillator
  263. """
  264. def oscillate(self, l):
  265. for pos in l:
  266. yield np.cos(2 * pi * pos)
  267. class Saw(YOscillator):
  268. """
  269. Saw wave oscillator
  270. """
  271. def oscillate(self, l):
  272. for pos in l:
  273. yield pos * 2.0 - 1.0
  274. class RevSaw(YOscillator):
  275. """
  276. Reverse Saw wave oscillator
  277. """
  278. def oscillate(self, l):
  279. for pos in l:
  280. yield -(pos * 2.0 - 1.0)
  281. class Square(YOscillator):
  282. """
  283. Square wave oscillator
  284. """
  285. def oscillate(self, l):
  286. for pos in l:
  287. #yield 1.0 if pos < 0.5 else -1.0
  288. pos = pos - 0.5
  289. yield -(np.abs(pos) / pos)
  290. class Pulse(YOscillator):
  291. """
  292. Pulse oscillator
  293. """
  294. def oscillate(self, l):
  295. zi = [1.0]
  296. for pos in l:
  297. pos, zi = lfilter([-1, 1], [1], pos, zi=zi)
  298. yield np.array(pos > 0, dtype=float)