# Can someone build an efficient drum machine?

**URL:** <https://in-thread.sonic-pi.net/t/can-someone-build-an-efficient-drum-machine/775>\
**Category:** \[P\] Patreon Support\
**Created:** [February 17, 2018, 8:57pm UTC](https://in-thread.sonic-pi.net/t/can-someone-build-an-efficient-drum-machine/775 "2018-02-17T20:57:00Z")\
**Posts on this page:** 1\
**Showing post:** 15

<div class="post-metadata">

**Author:** ![textchimp](https://avatars.discourse-cdn.com/v4/letter/t/b77776/32.png) [@textchimp](https://in-thread.sonic-pi.net/u/textchimp)\
**Post date:** [August 20, 2018, 4:27am UTC](https://in-thread.sonic-pi.net/t/can-someone-build-an-efficient-drum-machine/775/15 "2018-08-20T04:27:34Z")

</div>

Hey @ds604, just stumbled across this, and really like it as a very short & simple yet still visually intuitive drum machine.

Here’s an even shorter version, inspired by yours:

```ruby
use_bpm 120

def beats(pat)
  pat.delete(' ').split('').map(&:to_i).ring
end

patt = {
  :bd_klub => "9--5 --5- ---- -3-- 9--- ---- 9--- ----",
  :drum_snare_soft => "---- ---3 9--- ---- ---- ---- --33 9---",
  :perc_snap2 => "9--- --11 11-- ---- 5--- 5-11 11-- 9---",
  :elec_flip => "--5- ---- --5- --5- --5- ---- --5- --5-",
  # :bd_boom => "9-3--"
}

live_loop :main do
  tick #(step: [0,1,1,1,1,1,2].choose) # change step of tick randomly for nice effect
  patt.each{ |key, val| sample key, amp: beats(val).look / 10.0 }
  sleep 0.25
end

```

Turning the beat numbers directly into amplitudes makes it easy to control accents for each beat. I also used a loop to play each sample, shortened the beat-parsing function, and folded the separate instruments hash into keys of the pattern hash.

Thanks for a drum machine short and clear enough to teach in a class session!

**Update: okay, I think this is the shortest and clearest version I can come up with. Gets rid of the pattern hash entirely; everything is laid out in the loop body (this makes it easier to control the volume of each instrument individually, for example by adding “`* 0.5`” at the end of one of the “`amp:`” values:**

```ruby
def pat(p)
  p.delete(' ').split('').map{ |v| v.to_f / 10 }.ring
end

live_loop :machine do
  use_bpm 60
  tick
  sample :bd_klub, amp: pat(" 9--5 --5- ---- -3-- ").look
  sample :drum_snare_soft, amp: pat(" ---- ---3 9--- ---5 ").look
  sample :perc_snap2, amp: pat(" 9--- --11 11-- ---- ").look
  sample :elec_flip, amp: pat(" --5- ---- --5- --5- ").look
  sleep 0.25
end

```

---

_[View the full topic](https://in-thread.sonic-pi.net/t/can-someone-build-an-efficient-drum-machine/775)._
