|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'picrate' |
| 4 | +# This sketch is a more involved use of AudioSamples to create a simple drum machine. |
| 5 | +# Click on the buttons to toggle them on and off. The buttons that are on will trigger |
| 6 | +# samples when the beat marker passes over their column. You can change the tempo by |
| 7 | +# clicking in the BPM box and dragging the mouse up and down. |
| 8 | +# We achieve the timing by using AudioOutput's playNote method and a cleverly written Instrument. |
| 9 | +# For more information about Minim and additional features, |
| 10 | +# visit http://code.compartmental.net/minim/ |
| 11 | +class DrumMachine < Processing::App |
| 12 | + load_libraries :minim, :tick |
| 13 | + java_import 'ddf.minim.Minim' |
| 14 | + java_import 'ddf.minim.ugens.Sampler' |
| 15 | + |
| 16 | + attr_reader :minim, :out, :kick, :snare, :hat, :bpm, :beat, :buttons |
| 17 | + attr_reader :kikRow, :snrRow, :hatRow |
| 18 | + def setup |
| 19 | + minim = Minim.new(self) |
| 20 | + @out = minim.getLineOut |
| 21 | + @hatRow = Array.new(16, false) |
| 22 | + @snrRow = Array.new(16, false) |
| 23 | + @kikRow = Array.new(16, false) |
| 24 | + @buttons = [] |
| 25 | + @bpm = 120 |
| 26 | + @beat = 0 |
| 27 | + # load all of our samples, using 4 voices for each. |
| 28 | + # this will help ensure we have enough voices to handle even |
| 29 | + # very fast tempos. |
| 30 | + kick = Sampler.new(data_path('BD.wav'), 4, minim) |
| 31 | + snare = Sampler.new(data_path('SD.wav'), 4, minim) |
| 32 | + hat = Sampler.new(data_path('CHH.wav'), 4, minim) |
| 33 | + |
| 34 | + # patch samplers to the output |
| 35 | + kick.patch(out) |
| 36 | + snare.patch(out) |
| 37 | + hat.patch(out) |
| 38 | + 16.times do |i| |
| 39 | + buttons << Rect.new(10 + i * 24, 50, hatRow, i) |
| 40 | + buttons << Rect.new(10 + i * 24, 100, snrRow, i) |
| 41 | + buttons << Rect.new(10 + i * 24, 150, kikRow, i) |
| 42 | + end |
| 43 | + # start the sequencer |
| 44 | + out.setTempo(bpm) |
| 45 | + out.playNote(0, 0.25, Tick.new) |
| 46 | + end |
| 47 | + |
| 48 | + def draw |
| 49 | + background(0) |
| 50 | + fill(255) |
| 51 | + # text(frameRate, width - 60, 20) |
| 52 | + |
| 53 | + buttons.each(&:draw) |
| 54 | + |
| 55 | + stroke(128) |
| 56 | + (beat % 4).zero? ? fill(200, 0, 0) : fill(0, 200, 0) |
| 57 | + |
| 58 | + # beat marker |
| 59 | + rect(10 + beat * 24, 35, 14, 9) |
| 60 | + end |
| 61 | + |
| 62 | + def mouse_pressed |
| 63 | + buttons.each(&:mouse_pressed) |
| 64 | + end |
| 65 | + |
| 66 | + def settings |
| 67 | + size(395, 200) |
| 68 | + end |
| 69 | +end |
| 70 | + |
| 71 | +DrumMachine.new |
0 commit comments